<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Factory extends CI_Controller {

	/** 工厂管理
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct(){
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('Factory_m','m');
		$this->pageSize =$this->config->item('pagenum');
		 $this->load->model('Externalbuy_m', 'buy_m'); //外采购
	 }
	
	function orderlist()
	{

		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = "";
		
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND factoryId = 1";	
			$this->tpl->assign("fID", 1);
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND factoryId = 2";	
			$this->tpl->assign("fID", 2);
		}
		
		if($_COOKIE["classid"]==12 || $_COOKIE["classid"]==13)	//工厂只看派过单的
		{
			$where.=" AND updateflag = 9";
			/*
			if($this->input->get('st')==3 || $this->input->get('st')==4 || $this->input->get('st')==5 || $this->input->get('st')==6 || $this->input->get('st')==7 || $this->input->get('st')==2)
			{
			
			}else{
				$dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
				$where.=" AND B.custom !=0";
			}*/
		}else{
			
		}

		if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k A.orderId LIKE  " . $r." " ;
                }
                $where .= ")";

            } else {
                $where .= " and  (
					 A.orderId LIKE  '" . $other . "'
					
					) ";
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }

		if ($this->input->get_post('tradeid')) {
            $tradeid = trim($this->input->get_post('tradeid'));
            if (strstr($tradeid, ",")) {
                $tradeids = explode(",", $tradeid);
                $where .= " and (";
                foreach ($tradeids as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k  `dealid` LIKE  '%" . $r."%' or `backdealid` LIKE  '%" . $r."%'" ;
                }
                $where .= ")";

            } else {
                $where .= " and  (
					 `dealid` LIKE '%".$tradeid."%'
					 or `customerId` LIKE '%".$tradeid."%'
					 or `backdealid`LIKE '%".$tradeid."%'
					 or `mabangorderid`='".$tradeid."'
					) ";
            }
            $this->tpl->assign("tradeid", trim($this->input->get_post('tradeid')));
        }

		if ($this->input->get_post('customerId')) {
			$customerId = trim($this->input->get_post('customerId'));
			$where.=" AND customerId = '".$customerId."'";
			$this->tpl->assign("customerId", trim($this->input->get_post('customerId')));
		}

		if ($this->input->get_post('csvlist')) {
			$csvlist = substr($this->input->get_post('csvlist'),0,-1);
			 $where .= " AND A.orderId in($csvlist)";
		}
		if($this->input->get_post('cancel_flag')){
			$cancel_flag = trim($this->input->get_post('cancel_flag'));
			$where .= " AND A.cancel_flag = $cancel_flag ";
			$this->tpl->assign("cancel_flag",$cancel_flag);
		}
		
		if ($this->input->get_post('isinvalid')) {
			$isinvalid = trim($this->input->get_post('isinvalid'));
			
			$this->tpl->assign("isinvalid",2);
		}

		
		if($this->input->get_post('shopname'))
		{
			$where.=" AND shopId = '". trim($this->input->get_post('shopname'))."'";
			$this->tpl->assign("shopname", trim($this->input->get_post('shopname')));
		}
		if($this->input->get_post('fID'))
		{
			$where.=" AND factoryId = '". trim($this->input->get_post('fID'))."'";
			$this->tpl->assign("fID", trim($this->input->get_post('fID')));
		}
		
		if($this->input->get('ty')==1 || $this->input->get('ty')=='') $tys = 'orderTime';
		if($this->input->get('ty')==2) $tys = 'deliveryTime';
		if($this->input->get('ty')==3) $tys = 'shopmenttime';
		if($this->input->get('ty')==4) $tys = 'finshtime';
			$this->tpl->assign("ty", trim($this->input->get_post('ty')));
			$starttime = trim($this->input->get('starttime'));
			if ($starttime) {
				$times = $starttime . " 00:00:00";
				$where .= " AND ($tys >= '" . $times . "')";
				$this->tpl->assign("starttime", $starttime);
			}

			$endtime = trim($this->input->get('endtime'));
			if ($endtime) {
				$times = $endtime . " 23:59:59";
				$where .= " AND ($tys <= '" . $times. "')";
				$this->tpl->assign("endtime", $endtime);
			}
	
		if($this->input->get_post('st'))
		{
			if($this->input->get_post('st') ==6)
			{
				$where.=" AND orderurgent = '-4'";
			}elseif($this->input->get_post('st') ==7){
				$where.=" AND orderurgent = '-5' AND status = 2";
			}elseif($this->input->get_post('st') ==8){
				$where.=" AND updateflag =0 ";
			}elseif($this->input->get_post('st') ==9){
				$where.=" AND orderurgent ='18' and orderurgenttip=1 and (status=2 or status=1)";
			}elseif($this->input->get_post('st') ==1){
				if($_COOKIE["classid"]==12 || $_COOKIE["classid"]==13)	//工厂只看派过单的
				{
					//$dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
					$where.=" AND status = 1 AND updateflag =9";
				}else{
					$where.=" AND status = 1 ";
				}
			}else{
				$where.=" AND status = '". trim($this->input->get_post('st'))."'";
			}
			$this->tpl->assign("status", trim($this->input->get_post('st')));
		}
		$produce_status = trim($this->input->get_post("produce_status"));
		if($produce_status){
			$where.= " AND A.produce_status = {$produce_status} ";
			$this->tpl->assign("produce_status",$produce_status);
		}

		if($this->input->get_post('kw'))
		{
			 $goodsku = trim($this->input->get_post('kw'));
			 $this->tpl->assign("goodsku",$goodsku);
			 $dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
			 $where.=" AND B.goods_sku = '".$goodsku."'";
		}
		if($this->input->get_post('wk'))
		{
			 $wk = trim($this->input->get_post('wk'));
			 $dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
			 $where.=" AND B.proWorker = '".$wk."'";
			 $this->tpl->assign("wk",$wk);
		}
		if($this->input->get_post('cj'))
		{
			 $cj =trim($this->input->get_post('cj'));
			 $dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
			 $where.=" AND B.person1 = '".$cj."'";
			 $this->tpl->assign("cj",$cj);

		}
		if($this->input->get('orderby'))
		{
			$orderbyst = $this->input->get('orderby');
			if($orderbyst ==1)
			{
				$orderby = " order by A.orderTime ASC";
				$this->tpl->assign("orderbyst",2);
			}else{
				$orderby = " order by A.orderTime DESC";
				$this->tpl->assign("orderbyst",1);
			}
		}else{
			$orderby = " order by A.id DESC";
			$this->tpl->assign("orderby",1);
		}
		if($isinvalid==2)
		{
			$orderby = " order by A.orderTime ASC";
			$model = $this->input->get_post('model');//版型
			$gender1 = $this->input->get_post('gender1');//性别
			$size = $this->input->get_post('size');//尺码
			
			$dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
			if($model){
				$where.=" AND B.model = '".$model."'";
			}
			if($gender1){
				$where.=" AND B.gender1 = '".$gender1."'";
			}
			if($size){
				$where.=" AND B.size = '".$size."'";
			}
			$this->pageSize = $this->input->get_post('invalidNum')?$this->input->get_post('invalidNum'):100;
		}
		if($this->input->get('if_csv'))
		{
			$if_csv = 1;
		}
        $list = $this->fun->getalllist("db_factory_order A $dbname", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"A.*");

		foreach($list["list"] as $key=>$rs)
		{
			 switch ($rs["status"]) {
                case 1;
                    $list["list"][$key]["statustext"] = '新订单';
					break;
				case 2:
					$list["list"][$key]["statustext"] = '生产中';
					break;
				case 3:
					$list["list"][$key]["statustext"] = '生产完成';
					break;
				case 4:
					$list["list"][$key]["statustext"] = '已发货';
					break;
				case 5:
					$list["list"][$key]["statustext"] = '作废单';
					break;
			 }
			 $list["list"][$key]["orderTime"] = date("Y-m-d",strtotime($rs["orderTime"]));
		     $factorylist =  $this->fun->getdatabasesdetail("db_factory"," AND id='".$rs["factoryId"]."'");
			 $list["list"][$key]["factoryl"]  = $factorylist["name"];
			 $goodslist = $this->fun->getdatabasesdetail("db_factory_sell A LEFT JOIN db_goods B on A.goods_sku=B.goods_sku"," AND A.orderId='".$rs["id"]."'",'A.goods_sku,A.skuName,B.goods_id,A.person1,A.proWorker');
			 $list["list"][$key]["goods_sku"] = $goodslist["goods_sku"];
			 $list["list"][$key]["skuName"] = $goodslist["skuName"];

			
			$list["list"][$key]["person1"] = $goodslist["person1"];
			$list["list"][$key]["proWorker"] = $goodslist["proWorker"];


			  $goods_images = $this->db->get_where('db_goods_images', "goods_id='".$goodslist["goods_id"]."'")->result_array();
			   $thumb_url = $goods_images[0]["thumb_url"];
				if ($thumb_url) {
					 $list["list"][$key]["thumb_url"] = $thumb_url;
					 $list["list"][$key]["local_url"] = $goods_images[0]["local_url"];
				} else {
					$list["list"][$key]["thumb_url"] = "/fuman/images/s-l500.jpg";
				}

				$shop =  $this->fun->getdatabasesdetail("d_shop"," AND name='".$rs["shopId"]."'");	//负责人
				$list["list"][$key]["responsible"] = $shop["updateoper"];
			}
		if($this->input->get('if_csv'))
		{
			$headers =array("订单编号","交易编号","商品编号","商品名称","客户姓名","客户国家(中)","客户国家(英)","店铺","工厂","平台","备注");
			foreach($list["list"] as $key=>$rs)
			{
			$listdata[$key][] = $rs["orderId"]; 
			$listdata[$key][] = $rs["backdealid"]; 
			$listdata[$key][] = $rs["goods_sku"]; 
			$listdata[$key][] = $rs["skuName"]; 
			$listdata[$key][] = $rs["customerName"]; 
			$listdata[$key][] = $rs["country"]; 
			$listdata[$key][] = $rs["engCountry"]; 
			$listdata[$key][] = $rs["shopId"]; 
			$listdata[$key][] = $rs["factoryl"]; 
			$listdata[$key][] = $rs["platformId"]; 
			$listdata[$key][] = $rs["descr"]; 
			}
			$this->fun->ouputexclePro($headers,$listdata);
		}
		

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
		$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop',' AND del_flag= 0','id,name',' order by name asc'));			//查所有店铺
        $this->tpl->assign("orderlist", $list["list"]);


		

		if($this->input->get('fID')==1)
		{
			$wheregongc = "(department =13 AND classid = 12) or id=218 ";
			$wherecaijian= "(department =10 AND classid = 12) or id=218 ";
		}elseif($this->input->get('fID')==2)
		{
			$wheregongc = "(department =13 AND classid = 13) or id=218 ";
			$wherecaijian= "(department =10 AND classid = 13) or id=218 ";
		}else{
			if($_COOKIE["classid"]==12)
			{
				$wheregongc = "(department =13 AND classid = 12) or id=218 ";
				$wherecaijian= "(department =10 AND classid = 12) or id=218 ";
			}elseif($_COOKIE["classid"]==13)
			{
				$wheregongc = "(department =13 AND classid = 13) or id=218 ";
				$wherecaijian= "(department =10 AND classid = 13) or id=218 ";
			}else{
				$wheregongc = "(department =13 ) or id=218 ";
				$wherecaijian= "(department =10) or id=218 ";
			}
			
		}
	
		$this->tpl->assign("workers", $this->db->get_where('d_user',$wheregongc)->result_array());
		$this->tpl->assign("caijian", $this->db->get_where('d_user',$wherecaijian)->result_array());
		$this->tpl->assign("zhijian", $this->db->get_where('d_user',array('department'=>11))->result_array());
        $this->tpl->display("factory/orderlist.tpl");
	}
	
	function urgentorder()
	{
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = " and (status = 2 or status = 1) and orderurgent =17";
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND factoryId = 1  ";	
			$this->tpl->assign("fID", 1);
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND factoryId = 2 ";	
			$this->tpl->assign("fID", 2);
		}
		
		
		if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
            if (strstr($other, ",")) {
                $others = explode(",", $other);
                $where .= " and (";
                foreach ($others as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k A.orderId LIKE  " . $r." " ;
                }
                $where .= ")";

            } else {
                $where .= " and  (
					 A.orderId LIKE  '" . $other . "'
					
					) ";
            }
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }

		if ($this->input->get_post('tradeid')) {
            $tradeid = trim($this->input->get_post('tradeid'));
            if (strstr($tradeid, ",")) {
                $tradeids = explode(",", $tradeid);
                $where .= " and (";
                foreach ($tradeids as $key => $r) {
                    if ($key > 0) $k = "or";
                    $where .= " $k  `dealid` LIKE  '%" . $r."%' or `backdealid` LIKE  '%" . $r."%'" ;
                }
                $where .= ")";

            } else {
                $where .= " and  (
					 `dealid` LIKE '%".$tradeid."%'
					 or `customerId` LIKE '%".$tradeid."%'
					 or `backdealid`LIKE '%".$tradeid."%'
					 or `mabangorderid`='".$tradeid."'
					) ";
            }
            $this->tpl->assign("tradeid", trim($this->input->get_post('tradeid')));
        }

		if ($this->input->get_post('customerId')) {
			$customerId = trim($this->input->get_post('customerId'));
			$where.=" AND customerId = '".$customerId."'";
			$this->tpl->assign("customerId", trim($this->input->get_post('customerId')));
		}

		if ($this->input->get_post('csvlist')) {
			$csvlist = substr($this->input->get_post('csvlist'),0,-1);
			 $where .= " AND A.orderId in($csvlist)";
		}
		
		if($this->input->get_post('shopname'))
		{
			$where.=" AND shopId = '". trim($this->input->get_post('shopname'))."'";
			$this->tpl->assign("shopname", trim($this->input->get_post('shopname')));
		}
		if($this->input->get_post('fID'))
		{
			$where.=" AND factoryId = '". trim($this->input->get_post('fID'))."'";
			$this->tpl->assign("fID", trim($this->input->get_post('fID')));
		}
		
		if($this->input->get('ty')==1 || $this->input->get('ty')=='') $tys = 'orderTime';
		if($this->input->get('ty')==2) $tys = 'deliveryTime';
		if($this->input->get('ty')==3) $tys = 'shopmenttime';
		if($this->input->get('ty')==4) $tys = 'finshtime';
			$this->tpl->assign("ty", trim($this->input->get_post('ty')));
			$starttime = trim($this->input->get('starttime'));
			if ($starttime) {
				$times = $starttime . " 00:00:00";
				$where .= " AND ($tys >= '" . $times . "')";
				$this->tpl->assign("starttime", $starttime);
			}

			$endtime = trim($this->input->get('endtime'));
			if ($endtime) {
				$times = $endtime . " 23:59:59";
				$where .= " AND ($tys <= '" . $times. "')";
				$this->tpl->assign("endtime", $endtime);
			}
	
		if($this->input->get_post('st'))
		{
			if($this->input->get_post('st') ==6)
			{
				$where.=" AND orderurgent = '-4'";
			}elseif($this->input->get_post('st') ==7){
				$where.=" AND orderurgent = '-5' AND status = 2";
			}elseif($this->input->get_post('st') ==8){
				$where.=" AND updateflag =0 ";
			}elseif($this->input->get_post('st') ==1){
				if($_COOKIE["classid"]==12 || $_COOKIE["classid"]==13)	//工厂只看派过单的
				{
					//$dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
					$where.=" AND status = 1 AND updateflag =9";
				}else{
					$where.=" AND status = 1 ";
				}
			}else{
				$where.=" AND status = '". trim($this->input->get_post('st'))."'";
			}
			$this->tpl->assign("status", trim($this->input->get_post('st')));
		}

		if($this->input->get_post('kw'))
		{
			 $goodsku = trim($this->input->get_post('kw'));
			 $this->tpl->assign("goodsku",$goodsku);
			 $dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
			 $where.=" AND B.goods_sku = '".$goodsku."'";
		}
		if($this->input->get_post('wk'))
		{
			 $wk = trim($this->input->get_post('wk'));
			 $dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
			 $where.=" AND B.proWorker = '".$wk."'";
			 $this->tpl->assign("wk",$wk);
		}
		if($this->input->get_post('cj'))
		{
			 $cj =trim($this->input->get_post('cj'));
			 $dbname = " LEFT JOIN db_factory_sell B ON A.id = B.orderId";
			 $where.=" AND B.person1 = '".$cj."'";
			 $this->tpl->assign("cj",$cj);

		}
		if($this->input->get('orderby'))
		{
			$orderbyst = $this->input->get('orderby');
			if($orderbyst ==1)
			{
				$orderby = " order by A.orderTime ASC";
				$this->tpl->assign("orderbyst",2);
			}else{
				$orderby = " order by A.orderTime DESC";
				$this->tpl->assign("orderbyst",1);
			}
		}else{
			$orderby = " order by A.id DESC";
			$this->tpl->assign("orderby",1);
		}

		if($this->input->get('if_csv'))
		{
			$if_csv = 1;
		}
        $list = $this->fun->getalllist("db_factory_order A $dbname", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"A.*");
		foreach($list["list"] as $key=>$rs)
		{
			 switch ($rs["status"]) {
                case 1;
                    $list["list"][$key]["statustext"] = '新订单';
					break;
				case 2:
					$list["list"][$key]["statustext"] = '生产中';
					break;
				case 3:
					$list["list"][$key]["statustext"] = '生产完成';
					break;
				case 4:
					$list["list"][$key]["statustext"] = '已发货';
					break;
				case 5:
					$list["list"][$key]["statustext"] = '作废单';
					break;
			 }
			 $list["list"][$key]["orderTime"] = date("Y-m-d",strtotime($rs["orderTime"]));
		     $factorylist =  $this->fun->getdatabasesdetail("db_factory"," AND id='".$rs["factoryId"]."'");
			 $list["list"][$key]["factoryl"]  = $factorylist["name"];
			 $goodslist = $this->fun->getdatabasesdetail("db_factory_sell A LEFT JOIN db_goods B on A.goods_sku=B.goods_sku"," AND A.orderId='".$rs["id"]."'",'A.goods_sku,A.skuName,B.goods_id');
			 $list["list"][$key]["goods_sku"] = $goodslist["goods_sku"];
			 $list["list"][$key]["skuName"] = $goodslist["skuName"];
			  $goods_images = $this->db->get_where('db_goods_images', "goods_id='".$goodslist["goods_id"]."'")->result_array();
			   $thumb_url = $goods_images[0]["thumb_url"];
				if ($thumb_url) {
					 $list["list"][$key]["thumb_url"] = $thumb_url;
					 $list["list"][$key]["local_url"] = $goods_images[0]["local_url"];
				} else {
					$list["list"][$key]["thumb_url"] = "/fuman/images/s-l500.jpg";
				}

				$shop =  $this->fun->getdatabasesdetail("d_shop"," AND name='".$rs["shopId"]."'");	//负责人
				$list["list"][$key]["responsible"] = $shop["updateoper"];
			}
		if($this->input->get('if_csv'))
		{
			$headers =array("订单编号","交易编号","商品编号","商品名称","客户姓名","客户国家(中)","客户国家(英)","店铺","工厂","平台","备注");
			foreach($list["list"] as $key=>$rs)
			{
			$listdata[$key][] = $rs["orderId"]; 
			$listdata[$key][] = $rs["backdealid"]; 
			$listdata[$key][] = $rs["goods_sku"]; 
			$listdata[$key][] = $rs["skuName"]; 
			$listdata[$key][] = $rs["customerName"]; 
			$listdata[$key][] = $rs["country"]; 
			$listdata[$key][] = $rs["engCountry"]; 
			$listdata[$key][] = $rs["shopId"]; 
			$listdata[$key][] = $rs["factoryl"]; 
			$listdata[$key][] = $rs["platformId"]; 
			$listdata[$key][] = $rs["descr"]; 
			}
			$this->fun->ouputexclePro($headers,$listdata);
		}
		

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
		$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop',' AND del_flag= 0','id,name',' order by name asc'));			//查所有店铺
        $this->tpl->assign("orderlist", $list["list"]);


		

		if($this->input->get('fID')==1)
		{
			$wheregongc = "(department =13 AND classid = 12) or id=218 ";
			$wherecaijian= "(department =10 AND classid = 12) or id=218 ";
		}elseif($this->input->get('fID')==2)
		{
			$wheregongc = "(department =13 AND classid = 13) or id=218 ";
			$wherecaijian= "(department =10 AND classid = 13) or id=218 ";
		}else{
			if($_COOKIE["classid"]==12)
			{
				$wheregongc = "(department =13 AND classid = 12) or id=218 ";
				$wherecaijian= "(department =10 AND classid = 12) or id=218 ";
			}elseif($_COOKIE["classid"]==13)
			{
				$wheregongc = "(department =13 AND classid = 13) or id=218 ";
				$wherecaijian= "(department =10 AND classid = 13) or id=218 ";
			}else{
				$wheregongc = "(department =13 ) or id=218 ";
				$wherecaijian= "(department =10) or id=218 ";
			}
			
		}
	
		$this->tpl->assign("workers", $this->db->get_where('d_user',$wheregongc)->result_array());
		$this->tpl->assign("caijian", $this->db->get_where('d_user',$wherecaijian)->result_array());
		$this->tpl->assign("zhijian", $this->db->get_where('d_user',array('department'=>11))->result_array());
        $this->tpl->display("factory/urgentorderlist.tpl");
		
	}
	/*******工厂日常支出记录************/
	function addexpend()
	{
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		
		$where="";
		/**
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND factoryId = 12";	
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND factoryId = 13";	
		}**/

		if($_COOKIE["classid"]==12)
		{
			if($_COOKIE['department']==5){ //工厂财务都可以看到

			}else{
				$where.=" AND factoryId =12";
			}

		}
		if($_COOKIE["classid"]==13)
		{
			if($_COOKIE['department']==5){ //工厂财务都可以看到

			}else{
				$where.=" AND factoryId =13";
			}

		}

		if($this->input->get_post('fID'))
		{
			$where.=" AND factoryId = '". trim($this->input->get_post('fID'))."'";
			$this->tpl->assign("fID", trim($this->input->get_post('fID')));
		}
		
		if($this->input->get_post('st'))
		{
			$where.=" AND type = '". trim($this->input->get_post('st'))."'";
			$this->tpl->assign("type", trim($this->input->get_post('st')));
		}
		
		

		if($this->input->get('ty')==1 || $this->input->get('ty')=='') $tys = 'outtime';
		if($this->input->get('ty')==2) $tys = 'expenddate';
		$this->tpl->assign("ty", trim($this->input->get_post('ty')));
			$starttime = trim($this->input->get('starttime'));
			if ($starttime) {
				$times = $starttime . " 00:00:00";
				$where .= " AND ($tys >= '" . $times . "')";
				$this->tpl->assign("starttime", $starttime);
			}

			$endtime = trim($this->input->get('endtime'));
			if ($endtime) {
				$times = $endtime . " 23:59:59";
				$where .= " AND ($tys <= '" . $times. "')";
				$this->tpl->assign("endtime", $endtime);
			}
		
		if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
           
                $where .= " and  (
					    descr LIKE  '" . $other . "'
					 or type LIKE '%".$other."%'
					 or projeck LIKE '%".$other."%'
					 or supplier='".$other."'
					) ";
        
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }

		if($this->input->get('if_csv'))
		{
			$if_csv =1;
		}

		$allprice =$allnum=$alstprice= 0;
		$list = $this->fun->getalllist("db_expend", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"*");
		foreach($list["list"] as $key=>$rs)
		{
			if($rs["outtime"])
			{
				$list["list"][$key]["outtime"] = str_replace("00:00:00","",$rs["outtime"]);
			}

		}
		//获取总计
		$alldata = $this->fun->getdatabaseslist("db_expend",$where,"outmoney,price,num");
		if(count($alldata)>0)
		{
			foreach($alldata as $key=>$rs)
			{
				$allprice = $allprice + $rs["outmoney"];
				$alstprice = $alstprice + $rs["price"];
				$allnum = $allnum + $rs["num"];
			}
		}

		if($this->input->get('if_csv'))
		{
			$headers =array("支出日期","开票日期","类型","项目名称","价格","数量","支出金额","描述","供应商","工号","部门","操作时间");
			foreach($list["list"] as $key=>$rs)
			{
				if($rs['factoryid']==11)$factoryid="工厂1";
				if($rs['factoryid']==12)$factoryid="工厂2";
				$listdata[$key][] = $rs["outtime"]; 
				$listdata[$key][] = $rs["expenddate"]; 
				$listdata[$key][] = $rs["type"]; 
				$listdata[$key][] = $rs["projeck"]; 
				$listdata[$key][] = $rs["price"]; 
				$listdata[$key][] = $rs["num"]; 
				$listdata[$key][] = $rs["outmoney"]; 
				$listdata[$key][] = $rs["descr"]; 
				$listdata[$key][] = $rs["supplier"]; 
				$listdata[$key][] = $rs["oper"]; 
				$listdata[$key][] = $rs["factoryid"]; 
				$listdata[$key][] = $rs["opertime"]; 
				$alldate = $alldate+$rs["outmoney"];
			}
			$this->fun->ouputexclePro($headers,$listdata,$alldate);
		}

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("allprice", $allprice);
		$this->tpl->assign("allnum", $allnum);
		$this->tpl->assign("alstprice", $alstprice);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
		$this->tpl->assign("orderlist", $list["list"]);
		$this->tpl->display("factory/addexpend.tpl");
	}
	function scanorder()
	{
		
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		
		$where="";
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND factoryId = 1";	
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND factoryId = 2";
		}

		if($this->input->get_post('fID'))
		{
			$fid = trim($this->input->get_post('fID'));
			if($fid==12) $fie= 1;
			if($fid==13) $fie= 2;

				
			$where.=" AND factoryId = '".$fie."'";
			$this->tpl->assign("fID", trim($this->input->get_post('fID')));
		}
		
		if($this->input->get_post('ty'))
		{
			$where.=" AND type = '". trim($this->input->get_post('ty'))."'";
			$this->tpl->assign("ty", trim($this->input->get_post('ty')));
		}

		if($this->input->get_post('sts'))
		{
			$sts = $this->input->get_post('sts');
			if($sts==1)
			{
				$ststext = "insttime";
			}else{
				$ststext = "settlementtime";
			}
			$this->tpl->assign("sts", trim($this->input->get_post('sts')));
		}
		
			$starttime = trim($this->input->get('starttime'));
			if ($starttime) {
				$where .= " AND ($ststext >= '" . $starttime . "')";
				$this->tpl->assign("starttime", $starttime);
			}

			$endtime = trim($this->input->get('endtime'));
			if ($endtime) {
				$where .= " AND ($ststext <= '" . $endtime. "')";
				$this->tpl->assign("endtime", $endtime);
			}

		
		
		if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
           
                $where .= " and  (
					    goods_sku LIKE  '" . $other . "'
					 or skuName LIKE '%".$other."%'
					  or order_id LIKE '%".$other."%'
					
					) ";
        
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }

		if($this->input->get('if_csv'))
		{
			$if_csv =1;
		}

		$allprice =$allnum=$alstprice= 0;
		$list = $this->fun->getalllist("db_factory_scanorder", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"*");
		//$aaa = $this->fun->getalllist("db_factory_scanorder", $where, $nowpage, $if_csv, $this->pageSize, " group by specifications order by datatotal desc","count(*) as datatotal,specifications");
		//dump($aaa);
        //获取总计
		//$alldata = $this->fun->getdatabaseslist("db_factory_scanorder",$where,"price,goods_num");
		if(count($alldata)>0)
		{
			foreach($alldata as $key=>$rs)
			{
				$allprice = $allprice + $rs["outmoney"];
				$alstprice = $alstprice + $rs["price"];
				$allnum = $allnum + $rs["num"];
			}
		}

		if($this->input->get('if_csv'))
		{
			$headers =array("订单号","SKU","名称","数量","价格","规格","工厂","总价","操作时间","类型","操作人员");
			foreach($list["list"] as $key=>$rs)
			{
				if($rs['factoryID']==1)$factoryid="工厂1";
				if($rs['factoryID']==2)$factoryid="工厂2";
				if($rs['type']==2)$types="批量";
				if($rs['type']==1)$types="定制";
                if($rs['type']==2){
                    $priceinfo=$this->fun->getdatabasesdetail('db_goods'," and  goods_sku='$rs[goods_sku]'",'bulkprice');  
                     $rs["price"]=  $priceinfo['bulkprice'];
                }
				$listdata[$key][] = $rs["order_id"]; 
				$listdata[$key][] = $rs["goods_sku"]; 
				$listdata[$key][] = $rs["skuName"]; 
				$listdata[$key][] = $rs["goods_num"]; 
				$listdata[$key][] = $rs["price"]; 
				$listdata[$key][] = $rs["specifications"]; 
				$listdata[$key][] = $factoryid; 
                $listdata[$key][] = $rs["price"]*$rs["goods_num"]; 
				$listdata[$key][] = $rs["insttime"]; 
				$listdata[$key][] = $types; 
				$listdata[$key][] = $rs["oper"]; 

			}
			$this->fun->ouputexclePro($headers,$listdata,$alldate);
		}

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("allprice", $allprice);
		$this->tpl->assign("allnum", $allnum);
		$this->tpl->assign("alstprice", $alstprice);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
		$this->tpl->assign("orderlist", $list["list"]);
		$this->tpl->assign("usernames", $_COOKIE["username"]);
		$this->tpl->display("factory/scanorder.tpl");

	}
	function scanOrderRules(){
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		$where = "";
		$orderby = " ORDER BY priority asc,opertime desc ";
		$list = $this->fun->getalllist("db_factory_scanrules", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("orderlist", $list["list"]);
		$this->tpl->display("factory/scanorderrules.tpl");

	}
	function addScanRules(){
		$id = intval($this->input->get('id'));
		if($id){
			$res = $this->fun->getdatabasesdetail("db_factory_scanrules"," AND id='".$id."'");
			if($res["orderstatus"])
			{
				$res["orderstatus"] = explode(",",$res["orderstatus"]);
			}
		}else{
			$res["orderstatus"]  = array();
		}
		$express = $this->db->get_where("db_order_express","status=0")->result_array();
		$this->tpl->assign("express",$express);
		$this->tpl->assign("detail",$res);
		$this->tpl->display("factory/addscanrules.tpl");
	}
	function saveScanRules(){
		$this->m->saveScanRules();
		$this->fun->phpalert(4, "", '', "/factory/scanorderrules");
	}
	function revenue()
	{
		
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		/*只计算2017-5-24号之后的订单信息**/
		$where = " AND B.status = 3 AND B.finshtime>='2017-05-24 00:00:00'";
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND B.factoryId = 1";	
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND B.factoryId = 2";	
		}
		if($this->input->get_post('fID'))
		{
			$where.=" AND B.factoryId = '". trim($this->input->get_post('fID'))."'";
			$this->tpl->assign("fID", trim($this->input->get_post('fID')));
		}
		if($this->input->get_post('wk'))
		{
			 $wk = trim($this->input->get_post('wk'));
			 $where.=" AND A.proWorker = '".$wk."'";
			 $this->tpl->assign("wk",$wk);
		}
		if($this->input->get_post('cj'))
		{
			 $cj =trim($this->input->get_post('cj'));
			 $where.=" AND A.person1 = '".$cj."'";
			 $this->tpl->assign("cj",$cj);

		}
		if($this->input->get_post('other'))
		{
			 $other =trim($this->input->get_post('other'));
			 $where.=" AND B.orderId = '".$other."'";
			 $this->tpl->assign("other",$other);

		}

		if($this->input->get('ty')==1 || $this->input->get('ty')=='') $tys = 'orderTime';
		if($this->input->get('ty')==4) $tys = 'finshtime';
			$this->tpl->assign("ty", trim($this->input->get_post('ty')));
			$starttime = trim($this->input->get('starttime'));
			if ($starttime) {
				$times = $starttime . " 00:00:00";
				$where .= " AND ($tys >= '" . $times . "')";
				$this->tpl->assign("starttime", $starttime);
			}

			$endtime = trim($this->input->get('endtime'));
			if ($endtime) {
				$times = $endtime . " 23:59:59";
				$where .= " AND ($tys <= '" . $times. "')";
				$this->tpl->assign("endtime", $endtime);
			}
		if($this->input->get('if_csv'))
		{
			$if_csv = 1;
		}
		$allprice = $allmoney = 0;
		$list = $this->fun->getalllist("db_factory_sell A LEFT JOIN db_factory_order B ON A.orderId=B.id LEFT JOIN db_goods C ON A.goods_sku= C.goods_sku", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"A.*,B.orderId as ordernumber,B.finshtime,B.orderTime,B.shopmenttime,B.factoryId,C.g_costprice,C.goods_name,C.goods_id");
		foreach($list["list"] as $key=>$rs)
		{
			// $list["list"][$key]["orderTime"] = date("Y-m-d",strtotime($rs["orderTime"]));
		     $factorylist =  $this->fun->getdatabasesdetail("db_factory"," AND id='".$rs["factoryId"]."'");
			 $list["list"][$key]["factoryl"]  = $factorylist["name"];
			 if($rs["proWorker"])
			{
				$resproWorker = $this->fun->getdatabasesdetail('d_user'," AND id='".$rs["proWorker"]."'");
				 $list["list"][$key]["resproWorker"] = $resproWorker["name"];
			 }
			  if($rs["person1"])
			{
				$resproWorker = $this->fun->getdatabasesdetail('d_user'," AND id='".$rs["person1"]."'");
				 $list["list"][$key]["person1"] = $resproWorker["name"];
			 }
			   if($rs["person3"])
			{
				$resproWorker = $this->fun->getdatabasesdetail('d_user'," AND id='".$rs["person3"]."'");
				 $list["list"][$key]["person3"] = $resproWorker["name"];
			 }
			
			if($rs["cosprice"]>0)
			{
				$list["list"][$key]["g_costprice"]  = $rs["cosprice"];
			}
		 
		}

		//获取总计
		$alldata = $this->fun->getdatabaseslist("db_factory_sell A LEFT JOIN db_factory_order B ON A.orderId=B.id LEFT JOIN db_goods C ON A.goods_sku= C.goods_sku",$where,"price,cosprice,g_costprice");
		if(count($alldata)>0)
		{
			foreach($alldata as $key=>$rs)
			{
				if($rs["cosprice"]>0)
				{
					$cosprice = $rs["cosprice"];
				}else{
					$cosprice = $rs["g_costprice"];
				}
				$allprice = $allprice+$rs["price"];
				$allmoney = $allmoney+$cosprice;
			}
		}

		//print_r($list["list"]);
	
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("allprice", $allprice);
		$this->tpl->assign("allmoney", $allmoney);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
		$this->tpl->assign("orderlist", $list["list"]);
	
		if($this->input->get('if_csv'))
		{
			$headers =array("订单编号","完成日期","订单日期","生产方式","SKU","名称","生产工人","裁剪人员","质检人员","工价","出厂价","工厂");
			foreach($list["list"] as $key=>$rs)
			{
				if($rs["custom"]==1)$custom="均码";
				if($rs["custom"]==2)$custom="定制";
				if($rs["custom"]==3)$custom="配件";
				$listdata[$key][] = $rs["ordernumber"]; 
				$listdata[$key][] = $rs["finshtime"]; 
				$listdata[$key][] = $rs["orderTime"];
				$listdata[$key][] = $custom;
				$listdata[$key][] = $rs["goods_sku"]; 
				$listdata[$key][] = $rs["goods_name"]; 
				$listdata[$key][] = $rs["resproWorker"]; 
				$listdata[$key][] = $rs["person1"]; 
				$listdata[$key][] = $rs["person3"]; 
				$listdata[$key][] = $rs["price"]; 
				$listdata[$key][] = $rs["g_costprice"]; 
				$listdata[$key][] = $rs["factoryl"]; 
			}
			$this->fun->ouputexclePro($headers,$listdata);
		}

		if($this->input->get('fID')==1)
		{
			$wheregongc = "(department =13 AND classid = 12) or id=218 ";
			$wherecaijian= "(department =10 AND classid = 12) or id=218 ";
		}elseif($this->input->get('fID')==2)
		{
			$wheregongc = "(department =13 AND classid = 13) or id=218 ";
			$wherecaijian= "(department =10 AND classid = 13) or id=218 ";
		}else{
			if($_COOKIE["classid"]==12)
			{
				$wheregongc = "(department =13 AND classid = 12) or id=218 ";
				$wherecaijian= "(department =10 AND classid = 12) or id=218 ";
			}elseif($_COOKIE["classid"]==13)
			{
				$wheregongc = "(department =13 AND classid = 13) or id=218 ";
				$wherecaijian= "(department =10 AND classid = 13) or id=218 ";
			}else{
				$wheregongc = "(department =13 ) or id=218 ";
				$wherecaijian= "(department =10) or id=218 ";
			}
			
		}

		$this->tpl->assign("workers", $this->db->get_where('d_user',$wheregongc)->result_array());
		$this->tpl->assign("caijian", $this->db->get_where('d_user',$wherecaijian)->result_array());
		$this->tpl->assign("zhijian", $this->db->get_where('d_user',array('department'=>11))->result_array());
		$this->tpl->display("factory/revenue.tpl");
	}

	/*****工厂出货记录报表***/
	function ReportList()
	{
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		/*只计算2017-5-24号之后的订单信息**/
		$where = " AND B.status = 3 AND B.finshtime>='2017-05-24 00:00:00'";
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND B.factoryId = 1";	
		}
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND B.factoryId = 2";	
		}
		if($this->input->get_post('fID'))
		{
			$where.=" AND B.factoryId = '". trim($this->input->get_post('fID'))."'";
			$this->tpl->assign("fID", trim($this->input->get_post('fID')));
		}
		if($this->input->get_post('ls'))
		{
			 $ls = trim($this->input->get_post('ls'));
			 if($ls==1)	//负利润率
			{
				 $where.=" AND A.rate < 0";
			 }
			 if($ls==2)	//利润率0-0.1
			{
				 $where.=" AND A.rate < 0.1 AND A.rate >0";
			 }
			 if($ls==3)	//利润率无穷
			{
				 $where.=" AND A.rate > 0";
			 }
			
			 $this->tpl->assign("ls",$ls);
		}
	
		if($this->input->get_post('other'))
		{
			 $other =trim($this->input->get_post('other'));
			 $where.=" AND A.goods_sku = '".$other."'";
			 $this->tpl->assign("other",$other);
		}
		$status = trim($this->input->get_post("status"));
		if($status){
			$where.= " AND A.statuses = '".$status."'";
			$this->tpl->assign("status",$status);
		}
		if($this->input->get_post('lv'))
		{
			 $lv =trim($this->input->get_post('lv'));
			 $where.=" AND A.rate <= $lv";
			 $this->tpl->assign("lv",$lv);
		}
	
			$starttime = trim($this->input->get('starttime'));
			if ($starttime) {
				$times = $starttime . " 00:00:00";
				$where .= " AND (orderTime >= '" . $times . "')";
				$this->tpl->assign("starttime", $starttime);
			}

			$endtime = trim($this->input->get('endtime'));
			if ($endtime) {
				$times = $endtime . " 23:59:59";
				$where .= " AND (orderTime <= '" . $times. "')";
				$this->tpl->assign("endtime", $endtime);
			}

			$o_starttime = trim($this->input->get('o_starttime'));
			if ($o_starttime) {
				$times = $o_starttime . " 00:00:00";
				$where .= " AND (finshtime >= '" . $times . "')";
				$this->tpl->assign("o_starttime", $o_starttime);
			}

			$o_endtime = trim($this->input->get('o_endtime'));
			if ($o_endtime) {
				$times = $o_endtime . " 23:59:59";
				$where .= " AND (finshtime <= '" . $times. "')";
				$this->tpl->assign("o_endtime", $o_endtime);
			}


		
			
		if($this->input->get('if_csv'))
		{
			$if_csv = 1;
		}
		$allprice = $allmoney = 0;
		$list = $this->fun->getalllist("db_factory_sell A LEFT JOIN db_factory_order B ON A.orderId=B.id LEFT JOIN db_goods C ON A.goods_sku= C.goods_sku", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"A.*,B.orderId as ordernumber,B.finshtime,B.money,B.orderTime,B.shopmenttime,B.mabangorderid,B.factoryId,B.country,C.g_costprice,C.goods_name,C.goods_id");
		//echo $this->db->last_query();exit;
		foreach($list["list"] as $key=>$rs)
		{
		
			if($rs["country"]=='china' || $rs["country"]=='中国')
			{
				//$list["list"][$key]["shipingfee"] = $shipingfee= 20;
			}else{
				//$list["list"][$key]["shipingfee"] = $shipingfee= $rs["scale"] * 100;
			}
			
			 $factorylist =  $this->fun->getdatabasesdetail("db_factory"," AND id='".$rs["factoryId"]."'");
			 $list["list"][$key]["factoryl"]  = $factorylist["name"];
			
					if($rs["custom"] == 3)	//定制配件，不能以整套的价格
					{
						if($rs["cosprice"] ==0)
						{
							$g_costprice = $rs["g_costprice"];
						}else{
							$g_costprice = $rs["cosprice"];
						}
						
					}else{
						$g_costprice = $rs["g_costprice"];
					}
				
				$list["list"][$key]["g_costprice"] =$g_costprice;
			
			//如果是多个商品，金额只能以单个商品售价
			$orderList = $this->fun->getdatabasesdetail('db_order_sell A left JOIN db_order_list B on A.order_id = B.order_id'," AND B.order_sn = '".$rs["mabangorderid"]."'","count(rec_id) as id");
			if($orderList["id"]>1)
			{
				$moneys = $this->fun->getdatabasesdetail('db_order_sell A left JOIN db_order_list B on A.order_id = B.order_id'," AND B.order_sn = '".$rs["mabangorderid"]."' and A.goods_sn='".$rs["goods_sku"]."'","A.goods_amount,B.shipping_realfee,B.shipping_expectfee");
				if($moneys["goods_amount"]){
					$rs["money"] = $moneys["goods_amount"];
				}
				
			}
			$order = $this->fun->getdatabasesdetail('db_order_list'," AND order_sn = '".$rs["mabangorderid"]."' ","shipping_realfee,shipping_expectfee");
			
			if($order['shipping_realfee']>0)
			{
				$list["list"][$key]["shipingfee"] = $shipingfee= $order['shipping_realfee'];
			}else{
				$list["list"][$key]["shipingfee"] = $shipingfee= $order['shipping_expectfee'];
			}
			//利润率计算
			if($rs["money"]>0){
				$amount =($rs["money"]*0.835) - $shipingfee;
				if($amount !=0){

					$lv = ($amount - $g_costprice) / $amount;
					 $list["list"][$key]["lv"]  = round($lv,3);
				}else{
					 $list["list"][$key]["lv"]  = 0;
				}
			}else{
				 $list["list"][$key]["lv"]  = 0;
			}
			$list["list"][$key]["money"] = $rs["money"];
			//判断是否有修改过成本价
			 $loglist = $this->fun->getdatabasesdetail("db_goods_log"," AND goods_id='".$rs["goods_id"]."' AND types = 4" ,'*', " order by id DESC");
			if($loglist){
			 $list["list"][$key]["loglist"]  = $loglist["content"];
			}

		}

		
		//print_r($list["list"]);
	
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("allprice", $allprice);
		$this->tpl->assign("allmoney", $allmoney);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
		$this->tpl->assign("orderlist", $list["list"]);
		
		if($this->input->get('if_csv'))
		{
			$headers =array("订单编号","完成日期","订单日期","生产方式","SKU","名称","订单价格","订单重量","估计运费","销售利润率","出厂价","工厂","备注");
			foreach($list["list"] as $key=>$rs)
			{
				if($rs["custom"]==1)$custom="均码";
				if($rs["custom"]==2)$custom="定制";
				if($rs["custom"]==3)$custom="配件";
				$listdata[$key][] = $rs["ordernumber"]; 
				$listdata[$key][] = $rs["finshtime"]; 
				$listdata[$key][] = $rs["orderTime"];
				$listdata[$key][] = $custom;
				$listdata[$key][] = $rs["goods_sku"]; 
				$listdata[$key][] = $rs["goods_name"]; 
				$listdata[$key][] = $rs["money"]; 
				$listdata[$key][] = $rs["scale"]; 
				$listdata[$key][] = $rs["shipingfee"]; 
				$listdata[$key][] = $rs["lv"]; 
				$listdata[$key][] = $rs["g_costprice"]; 
				$listdata[$key][] = $rs["factoryl"]; 
				$listdata[$key][] = $rs["remark"]; 
			}
			$this->fun->ouputexclePro($headers,$listdata);
		}

		$this->tpl->display("factory/ReportList.tpl");
	}

	function orderdetail()
	{
		$id = intval($this->input->get('id'));
		$orderid = intval($this->input->get('orderid'));
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where=" AND factoryId = 1";	
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where=" AND factoryId = 2";	
		}
		
		if($id){
			$detail = $this->fun->getdatabasesdetail("db_factory_order"," AND id='".$id."' $where");//订单详细
		}else{
			$detail = $this->fun->getdatabasesdetail("db_factory_order"," AND orderId='".$orderid."' $where");//订单详细
		}
		if($detail=="")
		{
			die('参数传递错误或你无权查看该订单！<input type="button" name="back" value="返回上一页" onclick="javascript:history.back(-1);"/>');
		}
		switch ($detail["status"]) {
                case 1;
                    $detail["statustext"] = '新订单';
					break;
				case 2:
					$detail["statustext"]  = '生产中';
					break;
				case 3:
					$detail["statustext"]  = '生产完成';
					break;
				case 4:
					$detail["statustext"]  = '已发货';
					break;
				case 5:
					$detail["statustext"]  = '作废单';
					break;
		 }
		 $factorylist =  $this->fun->getdatabasesdetail("db_factory"," AND id='".$detail["factoryId"]."'");
		 $detail["factoryl"]  = $factorylist["name"];
		 $goodslist = $this->fun->getdatabasesdetail("db_factory_sell"," AND orderId='".$detail["id"]."'");
		 $detail["goods_sku"] = $goodslist["goods_sku"];
		 $detail["skuName"] = $goodslist["skuName"];
		if($goodslist["price"]=="0.00")
		{
		 $price =$this->fun->getdatabasesdetail("db_goods"," AND goods_sku='".$goodslist["goods_sku"]."'");
		 $goodslist["price"]  = round($price["wages"],2);
		}
		 $detail["sell"] = $goodslist; 
		
		 $goodsdetail = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku='".$goodslist["goods_sku"]."'",'goods_id');
		
		   $goods_images = $this->db->get_where('db_goods_images', 'goods_id=' . $goodsdetail["goods_id"])->result_array();
		   $thumb_url = $goods_images[0]["thumb_url"];
			if ($thumb_url) {
				 $detail["thumb_url"] = $thumb_url;
				 $detail["images_url"] = $goods_images[0]["images_url"];
			} else {
				 $detail["thumb_url"] = "/fuman/images/s-l500.jpg";
			}
		
		
		

		if($detail["factoryId"]==1) $classid = 12;
		if($detail["factoryId"]==2) $classid = 13;
		if($detail["factoryId"]=='') $classid = 0;
		//工人
		if($classid)
		{
			$where ="(department=13 AND classid = $classid) or id=218";
		}else{
			$where ="(department=13 ) or id=218";
		}
		$this->tpl->assign("workers", $this->db->get_where('d_user',$where)->result_array());
		$this->tpl->assign("zhijian", $this->db->get_where('d_user',array('department'=>11))->result_array());
		if($classid)
		{
			$where ="(department=10 AND classid = $classid) or id=218";
		}else{
			$where ="(department=10 ) or id=218";
		}
		$this->db->order_by("id", 'DESC');
		$orderlog = $this->db->get_where('db_factory_orderlog', 'orderId=' . $detail["id"])->result_array();
		$this->tpl->assign("caijian", $this->db->get_where('d_user',$where)->result_array());
		$this->tpl->assign("detail", $detail);
		$this->tpl->assign("orderlog", $orderlog);
		$this->tpl->assign('classid',$_COOKIE["classid"]);	//部门
		
		//均码信息
//		$goodslist = $this->fun->getdatabasesdetail("db_goods"," AND goods_parent_sku = '".$detail["goods_sku"]."' AND goods_sku !='".$detail["goods_sku"]."'","GROUP_CONCAT(goods_id) as goodsID");
//		if($goodslist["goodsID"])
//		{
//			$goodsIDs = $goodslist["goodsID"];
//			$arraygoodsList = $this->db->select("goods_id,goods_sku")->get_where('db_goods',"goods_id in($goodsIDs)")->result_array();
//			$this->tpl->assign("arraygoodsList", $arraygoodsList);
//		}
		
	    $this->tpl->display("factory/orderdetail.tpl");
	}

	function saveorder()
	{
		
		$id = $this->m->saveorder();
		 $this->fun->phpalert(4, "", '', "/factory/orderdetail?id={$id}");
         die;
	}
	/********************
	** 工厂订单错误日志
	** 
	********************/
	function orderlog()
	{
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = "";
		$orderby = " order by id DESC";
		if($this->input->get('t')==1)
		{
			 $list = $this->fun->getalllist('d_fmtask',  " AND flag = 1", $nowpage, $if_csv, $this->pageSize, $orderby);
		}else{
		     $list = $this->fun->getalllist('db_error_log',  " AND types = '工厂导入订单错误' AND isshow = 0", $nowpage, $if_csv, $this->pageSize, $orderby);
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlog", $list["list"]);
		
		if($this->input->get('t')==1)
		{
			$this->tpl->display("factory/orderlogyes.tpl");
		}else{
		   $this->tpl->display("factory/orderlog.tpl");
		}
	}
	/**************************
	*** 原工厂系统的订单商品表
	*** 只保存商品的ID号，为了
	*** 统一，需要临时将db_factory_product
	*** 表中的SKU更新到订单商品表(更新完后db_factory_product 表可删除)
	*** updateproductsell 和 updateproductshop 可删除
	*************************/
	
	function updateproductsell()
	{
		$goodslist = $this->db->get('db_factory_sell')->result_array();
		foreach($goodslist as $key=>$rs)
		{
			$rsdb = $this->fun->getdatabasesdetail("db_factory_product"," AND id='".$rs["skuID"]."'");
			if($rsdb)
			{
				$this->db->update("db_factory_sell",array("goods_sku"=>$rsdb["sku"]),"id=".$rs["id"]);
			}
		}
	}

	/**************************
	*** 原工厂系统的订单店铺编号和平台编号
	*** 不能对应马帮，为了
	*** 统一，需要临时将db_factory_shop
	*** 更新表中的数据 (更新完后db_factory_shop表 可删除)
	*** 更新完成后 updateproductshop 可删除
	*************************/
	function updateproductshopts()
	{
		$ordersell = $this->db->get('db_factory_sell')->result_array();
		foreach($ordersell as $key=>$rs)
		{
			$person1 = $rs["person1"];
			$proWorker = $rs["proWorker"];
			$person3 = $rs["person3"];

			if($proWorker)
			{
				if($proWorker=="75"|| $proWorker=="76")
				{
					$this->db->update("db_factory_sell",array("proWorker"=>218),"id=".$rs["id"]);	//更新店铺和
				}else{
					$res = $this->fun->getdatabasesdetail('d_user'," AND id='".$proWorker."' AND department =13");
					if($res)
					{
						continue;
					}

					$rsdb = $this->fun->getdatabasesdetail('db_factory_sysadmin'," AND id='".$proWorker."'");
					if($rsdb["name"])
					{
						$res = $this->fun->getdatabasesdetail('d_user'," AND name='".$rsdb["name"]."'");
						if($res)
						{
							$this->db->update("db_factory_sell",array("proWorker"=>$res["id"]),"id=".$rs["id"]);	//更新店铺和
						}
					}else{
						$this->db->update("db_factory_sell",array("proWorker"=>0),"id=".$rs["id"]);	//更新店铺和
					}
				}
			}
	}
	echo "OK";
	}
	function updateproductshop()
	{
		$platformid = array("1"=>'Ebay','2'=>'Amazon','4'=>'1号店','6'=>'Tmall','19'=>'Cdiscount','5'=>'淘宝','10'=>'aliexpress','13'=>'other','14'=>'Magento','16'=>'Wish');
		$platformidnum =11;
		
		//更新工厂
		
		$ordersell = $this->db->get('db_factory_sell')->result_array();
		foreach($ordersell as $key=>$rs)
		{
			$goodsno = $rs["goods_sku"];
			if(is_numeric($goodsno) && preg_match('|^\d{8}$|',$goodsno))	//数字并且8位
			{
				if(substr($goodsno,0,2)==11)
				{
					$supplier = 1;	//11开头的8位数字 工厂1
				}

				if(substr($goodsno,0,2)==12)
				{
					$supplier = 2; //12开头的8位数字 工厂2
				}
			}

			$this->db->update("db_factory_order",array("factoryId"=>$supplier),"id=".$rs["orderId"]);	//更新工厂

		}
	

		$orderlist = $this->db->get('db_factory_order')->result_array();
		foreach($orderlist as $key=>$rs)
		{
			$shop = $this->db->get_where('db_factory_shop',"id='".$rs["shopId"]."'")->result_array();
			
			//更新店铺信息 			//更新销售平台
			if($shop[0]["name"]){
				$shopname = $shop[0]["name"];
				$platformidnum =$shop[0]["platformid"];
				$platformidsa = $platformid[$platformidnum];
				$this->db->update("db_factory_order",array("platformId"=>$platformidsa,"shopId"=>$shopname),"id=".$rs["id"]);	//更新店铺和
			}
		}


		//更新质检人员
		$ordersell = $this->db->get('db_factory_sell')->result_array();
		foreach($ordersell as $key=>$rs)
		{
			$person1 = $rs["person1"];
			$proWorker = $rs["proWorker"];
			$person3 = $rs["person3"];

			if($person1)
			{
				if($person1=="75"|| $person1=="76")
				{
					$this->db->update("db_factory_sell",array("person1"=>218),"id=".$rs["id"]);	//更新店铺和
				}else{
					$rsdb = $this->fun->getdatabasesdetail('db_factory_sysadmin'," AND id='".$person1."'");
					if($rsdb["name"])
					{
						$res = $this->fun->getdatabasesdetail('d_user'," AND name='".$rsdb["name"]."'");
						if($res)
						{
							$this->db->update("db_factory_sell",array("person1"=>$res["id"]),"id=".$rs["id"]);	//更新店铺和
						}
					}else{
						$this->db->update("db_factory_sell",array("person1"=>0),"id=".$rs["id"]);	//更新店铺和
					}
				}
			}
			if($person3)
			{
				if($person3=="75"|| $person3=="76")
				{
					$this->db->update("db_factory_sell",array("person3"=>218),"id=".$rs["id"]);	//更新店铺和
				}else{
				$rsdb = $this->fun->getdatabasesdetail('db_factory_sysadmin'," AND id='".$person3."'");
				if($rsdb["name"])
				{
					$resperson3 = $this->fun->getdatabasesdetail('d_user'," AND name='".$rsdb["name"]."'");
					if($resperson3)
					{
						$this->db->update("db_factory_sell",array("person3"=>$resperson3["id"]),"id=".$rs["id"]);	//更新店铺和
					}
				}else{
						$this->db->update("db_factory_sell",array("person3"=>0),"id=".$rs["id"]);	//更新店铺和
					}
				}
			}
			if($proWorker)
			{
				if($proWorker=="75"|| $proWorker=="76")
				{
					$this->db->update("db_factory_sell",array("proWorker"=>218),"id=".$rs["id"]);	//更新店铺和
				}else{
					$rsdb = $this->fun->getdatabasesdetail('db_factory_sysadmin'," AND id='".$proWorker."'");
					if($rsdb["name"])
					{
						$resproWorker = $this->fun->getdatabasesdetail('d_user'," AND name='".$rsdb["name"]."'");
						if($resproWorker)
						{
							$this->db->update("db_factory_sell",array("proWorker"=>$resproWorker["id"]),"id=".$rs["id"]);	//更新店铺和
						}else{
							$this->db->update("db_factory_sell",array("proWorker"=>0),"id=".$rs["id"]);	//更新店铺和
						}
					}
				}
			}
		}

		echo "OK";
	}

	/******工厂物料管理*****/
	function material()
	{
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		
		$where="";
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			$where.=" AND factoryId = 12";	
		}
		
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$where.=" AND factoryId = 13";	
		}
		if($this->input->get_post('fID'))
		{
			$where.=" AND factoryId = '". trim($this->input->get_post('fID'))."'";
			$this->tpl->assign("fID", trim($this->input->get_post('fID')));
		}
		
		
		
		if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
           
                $where .= " and  (
					    projeck LIKE  '%" . $other . "%'
					 or code = '".$other."'
					 or supplier='".$other."'
					) ";
        
            $this->tpl->assign("other", trim($this->input->get_post('other')));
        }

		if($this->input->get('if_csv'))
		{
			$if_csv =1;
		}

		$allprice =$allnum=$alstprice= 0;
		$list = $this->fun->getalllist("db_factory_material", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"*");
		foreach($list["list"] as $key=>$rs)
		{
			if($rs["outtime"])
			{
				$list["list"][$key]["outtime"] = str_replace("00:00:00","",$rs["outtime"]);
			}
			if ($_COOKIE["username"] == $rs["oper"]) {
				$list["list"][$key]["mod"] = 1;
			} else {
				$list["list"][$key]["mod"] = 0;
			}

			//获取商品图片
			$ProductImages = $this->buy_m->getProductImages($rs["id"],$type=1);
			if($ProductImages)
			{
				$imgurl = dirname(__FILE__) . "/../..".$ProductImages[0]["thumb_url"];
				if(file_exists($imgurl))
				{
					$list["list"][$key]["images"] = $ProductImages[0]["thumb_url"];
				}else{
					$list["list"][$key]["images"] = "/fuman/images/s-l500.jpg";
				}
			}else{
				$list["list"][$key]["images"] = "/fuman/images/s-l500.jpg";
			}

		}
		//获取总计
		$alldata = $this->fun->getdatabaseslist("db_factory_material",$where,"price,num");
		if(count($alldata)>0)
		{
			foreach($alldata as $key=>$rs)
			{
				$alstprice = $alstprice + $rs["price"];
				$allnum = $allnum + $rs["num"];
			}
		}

		if($this->input->get('if_csv'))
		{
			$headers =array("支出日期","开票日期","类型","项目名称","价格","数量","支出金额","描述","供应商","工号","部门","操作时间");
			foreach($list["list"] as $key=>$rs)
			{
				if($rs['factoryid']==11)$factoryid="工厂1";
				if($rs['factoryid']==12)$factoryid="工厂2";
				$listdata[$key][] = $rs["outtime"]; 
				$listdata[$key][] = $rs["expenddate"]; 
				$listdata[$key][] = $rs["type"]; 
				$listdata[$key][] = $rs["projeck"]; 
				$listdata[$key][] = $rs["price"]; 
				$listdata[$key][] = $rs["num"]; 
				$listdata[$key][] = $rs["outmoney"]; 
				$listdata[$key][] = $rs["descr"]; 
				$listdata[$key][] = $rs["supplier"]; 
				$listdata[$key][] = $rs["oper"]; 
				$listdata[$key][] = $rs["factoryid"]; 
				$listdata[$key][] = $rs["opertime"]; 
				$alldate = $alldate+$rs["outmoney"];
			}
			$this->fun->ouputexclePro($headers,$listdata,$alldate);
		}

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("allprice", $allprice);
		$this->tpl->assign("allnum", $allnum);
		$this->tpl->assign("alstprice", $alstprice);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
		$this->tpl->assign("orderlist", $list["list"]);

		//获取所有的类别
		  $alltype = $this->db->select('typename')->group_by(' typename ')->get_where('db_factory_material'," factoryid = '".$_COOKIE["classid"]."'")->result_array();
		 if(count($alltype)>0)
		 {
			foreach($alltype as $rs)
			 {
				$newpres[] = $rs['typename'];
			}
		 }
		  $alltypenewsupplier = $this->db->select('supplier')->group_by(' supplier ')->get_where('db_factory_material'," factoryid = '".$_COOKIE["classid"]."'")->result_array();
		 if(count($alltypenewsupplier)>0)
		 {
			foreach($alltypenewsupplier as $rs)
			 {
				$newsupplier[] = $rs['supplier'];
			}
		 }
		 $this->tpl->assign("newtype", $newpres);
		  $this->tpl->assign("newsupplier", $newsupplier);
		  $this->tpl->display("factory/material.tpl");
	}
	
	function ajaxbutton()
	{
	
		$op = $this->input->get_post('op');
		//申请议价
		if($op == "apply2price"){
			$str_ids = trim($this->input->post("ids"),",");
			$arr_ids = explode(",",$str_ids);
			foreach($arr_ids as $k=>$v){
				$sql = "SELECT * FROM db_factory_sell WHERE id = {$v} ";
				$rs  = $this->db->query($sql)->row_array();
				if($rs["statuses"]>=1){ //申请议价以上
					continue;
				}
				$this->db->update("db_factory_sell",array("statuses"=>1)," id = {$v} ");
			}
			echo 200;exit;
		}
		if($op == "changePrice"){
			$id = trim($this->input->post("id"));
			$flag = trim($this->input->post("flag"));
			if($flag==1){ //维持原价
				$this->db->update("db_factory_sell",array("statuses"=>2)," id = {$id} ");
			}
			if($flag==3){
				//修改价格
				$this->db->trans_begin();
				$price = trim($this->input->post("price"));
				$sql = "SELECT b.goods_id,b.g_costprice FROM db_factory_sell a LEFT JOIN db_goods b ON a.goods_sku = b.goods_sku WHERE a.id = {$id} ";
				$rs  = $this->db->query($sql)->row_array();
				if($rs['g_costprice']<=$price){
					echo 201;exit;
				}
				$this->db->update("db_factory_sell",array("statuses"=>3)," id = {$id} ");

				$statuslist[9] = "修改价格";
				$this->fun->insertsysstatistical('status',9,$rs['goods_id'],0,$statuslist);
				//更新商品日志
				$this->db->update("db_goods",array("g_costprice"=>$price)," goods_id = '".$rs['goods_id']."'");
				$goodslog="";
				$goodslog["goods_id"] = $rs['goods_id'];	//更新商品表 日志信息
				$goodslog["updatetime"] = date("Y-m-d H:i:s");
				$goodslog["createUid"] = $_COOKIE['userid'];
				$goodslog["types"] = 4; //修改成本家
				$goodslog["old_data"] = $rs['g_costprice']; //成本价
				$goodslog["new_data"] = $price; //修改后价格
				$goodslog["content"] = "原成本：{$rs['g_costprice']},更新为：{$price},修改原因：申请议价";
				$goodslog["createUser"] =$_COOKIE['username'];
				$this->db->insert('db_goods_log', $goodslog);

				$goodslog="";
				$goodslog["goods_id"] = $rs['goods_id'];	//更新商品表 日志信息
				$goodslog["updatetime"] = date("Y-m-d H:i:s");
				$goodslog["createUid"] = $_COOKIE['userid'];
				$goodslog["types"] = 1; //修改成本家
				$goodslog["old_data"] = $rs['g_costprice']; //成本价
				$goodslog["new_data"] = $price; //修改后价格
				$goodslog["content"] = "原成本：{$rs['g_costprice']},更新为：{$price},修改原因：申请议价";
				$goodslog["createUser"] =$_COOKIE['username'];
				$this->db->insert('db_goods_log', $goodslog);


				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
				} else {
					$this->db->trans_commit();
				}

			}
			echo 200;exit;
		}
		if($op == 'stscanrule')
		{
			/********************************************
			 * 海外仓规则脚本停用 启用
			 ***********************************************/
			$id  = $this->input->get("id");
			$type  = $this->input->get("type");
			$this->db->update("db_factory_scanrules",array("status"=>$type),"id=".$id);
			header("location:/factory/scanOrderRules");
		}
		if($op == 'delscanrule')
		{
			/********************************************
			 * 海外仓规则脚本删除
			 ***********************************************/
			$id  = $this->input->get("id");
			$this->db->delete("db_factory_scanrules","id=".$id);
			header("location:/factory/scanOrderRules");
		}
		if($op =='printorder')
		{
			 $orderlist = $this->input->post('orderlist');
			 $orderlist =array_unique(array_filter(explode(",",$orderlist)));
			 $isclenr =  $this->input->post('isclenr');
			 $neworderlist = array();
			foreach($orderlist as $key=>$rs)
			{
				//更新备注
				$rsdb = $this->fun->getdatabasesdetail('db_factory_order'," AND orderId ='".trim($rs)."'");
				$resll =  $this->fun->getdatabasesdetail('db_factory_sell'," AND orderId ='".$rsdb["id"]."'");

				//查询订单列表里面是否为多件
				$tradeorder = $this->fun->getdatabasesdetail('db_order_list'," AND order_sn = '{$rsdb['mabangorderid']}' AND  tradeid ='".$rsdb['backdealid']."'");
				$sql_tradenum = "SELECT * FROM db_order_sell WHERE order_id = '{$tradeorder['order_id']}' ";
				$rs_tradenum  = $this->db->query($sql_tradenum)->result_array();
				//订单多件的时候 检测是否为工厂和其他平台采购商品的混合体
				if(count($rs_tradenum)>0){
					$goods_num = 0;
					$message = "";
					foreach($rs_tradenum as $key=>$value){
						$goods_num = $goods_num + $value['goods_number'];
						$rsdb_goods = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku ='".$value['goods_sn']."'",'goods_parent_sku,goods_name,goods_sku');
						$flag = substr($rsdb_goods['goods_parent_sku'],0,2);
						if(strlen($rsdb_goods['goods_parent_sku'])==8){
							if($flag=="11"||$flag=="12"){
							}else{
								$message .= $rsdb_goods['goods_sku'].",";
							}
						}else{
							$message .= $rsdb_goods['goods_sku'].",";
						}
					}
					if($message){
						$content = "";
						if($rsdb['descr']){
							$content = $rsdb['descr'].","."与外采购合发".$message;
						}else{
							$content = "与外采购合发,".$message;
						}
						$this->db->update("db_factory_order",array("descr"=>$content)," orderId ='".trim($rs)."'");
					}
				}


				//更新打印标签printflag
				if($isclenr==1)
				{
					$this->db->update("db_factory_order",array('printflag'=>0),"orderId='".trim($rs)."'");
				}else{
					$this->db->update("db_factory_order",array('printflag'=>1),"orderId='".trim($rs)."'");
				}
				$detail = $this->m->getfactoryorder(trim($rs));
				if($detail[0]["responsible"]){
					$rsdb = $this->fun->getdatabasesdetail("d_user"," AND name='".$detail[0]["responsible"]."'");
					if($rsdb["username"]){
					 $detail[0]["responsible"] = $rsdb["username"];
					}
				}
				$neworderlist[]= $detail[0];
				//echo "<img src=\"/fuman/barcode/html/image.php?filetype=PNG&dpi=72&scale=1&rotation=0&font_family=Arial.ttf&font_size=8&text=ts12312321321&thickness=30&checksum=1&code=BCGcode128\" alt=\"Barcode Image\" />";
				//print_r($detail);
				//die;
				
			}
			 $this->tpl->assign("neworderlist", $neworderlist);
			 $this->tpl->display("factory/printorder.tpl",0,0,1);
		}
		if($op =='batchendorder')
		{
			if($this->input->post('orderid')=="")
			{
				$this->fun->phpalert(2, "请输入订单号");
				die;
			}
			$orderid = $this->input->post('orderid');	//订单号
			$scale   = $this->input->post('scale');		//重量
			$person1 = $this->input->post('person1');	//裁剪人员
			$zhijian = $this->input->post('zhijian');	//质检人员
			$proWorker = $this->input->post('proWorker');//生产工人
			$wages = $this->input->post('wages');//工价
			$cosprice = $this->input->post('cosprice');//成本价
			if(count($orderid)==0)
			{
				$this->fun->phpalert(2, "请输入订单号");
				die;
			}
			if(count($scale)==0)
			{
				$this->fun->phpalert(2, "请输入重量");
				die;
			}
			if(count($person1)==0)
			{
				$this->fun->phpalert(2, "请输入裁剪人员");
				die;
			}
			if(count($zhijian)==0)
			{
				$this->fun->phpalert(2, "请输入质检人员");
				die;
			}
			if(count($proWorker)==0)
			{
				$this->fun->phpalert(2, "请输入生产工人");
				die;
			}
			if(count($wages)==0)
			{
				$this->fun->phpalert(2, "请输入工价");
				die;
			}
			
		
			
			$urlorder= "";
			foreach($orderid as $key=>$order)
			{
				if($order)
				{
						$rsdb = $this->fun->getdatabasesdetail('db_factory_order'," AND orderId = '".$order."'");
						$ordersn = $rsdb["mabangorderid"];//订单列表sn
						$postdata="";
						$postdata["scale"]  = $scale[$key];
						$postdata["person1"]  = $person1[$key];
						$postdata["person3"]  = $zhijian[$key];
						$postdata["proWorker"]  = $proWorker[$key];
						$postdata["price"]  = $wages[$key];
						$postdata["cosprice"]  = $cosprice[$key];
						
						if($rsdb["status"]==2){
							$this->db->update("db_factory_sell",$postdata," orderId='".$rsdb["id"]."'");
							$this->db->update('db_factory_order',array("status"=>3,"finshtime"=>date("Y-m-d H:i:s")),"orderId='".$order."'");
							$rsdbds = $this->fun->getdatabasesdetail("db_factory_order"," AND orderId='".$order."'");
							$str=" 工时：".$postdata["price"]."  重量 ".$postdata["scale"]." 成本 ".$postdata["cosprice"];
							 $this->db->insert("db_factory_orderlog",array("orderId"=>$rsdbds["id"],"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>'批量修改完成状态 '.$str,"spcodeid"=>1));

							 //计算利润率
							 if($rsdb["money"]>0){
								 $rssellgoods = $this->fun->getdatabasesdetail("db_factory_sell A left join db_goods B on A.skuID = B.goods_id"," AND orderId='".$rsdb["id"]."'"," A.* ,B.g_costprice");
								$amount =($rsdb["money"]*0.835) -($postdata["scale"]*100);
								if($amount !=0){
									if($rssellgoods["custom"]==3)	//配件成本
									{
										 $lv = ($amount - $rssellgoods["costprice"]) / $amount;
									}else{
										 $lv = ($amount - $rssellgoods["g_costprice"]) / $amount;
									}
									
									 $rate  = round($lv,3);
								}else{
									 $rate  = 0;
								}
							}
							$this->db->update("db_factory_sell",array("rate"=>$rate)," orderId='".$rsdb["id"]."'");
							//只要是定制配件自动更新商品成本价到订单成本
							
							if($this->config->item('isupdatecosprice')==1)	//系统设置自动同步商品成本
							{
								if($rssellgoods["custom"] ==3)
								{
									if($postdata["cosprice"]>0)
									{
											$rsOrder = $this->fun->getdatabasesdetail("db_order_list"," AND order_sn = '".$ordersn."'","order_id");
											if($rsOrder['order_id']>0)
											{
												$rsSell = $this->fun->getdatabasesdetail("db_order_sell"," AND order_id = '".$rsOrder['order_id']."' AND goods_id='".$rssellgoods["skuID"]."' ","rec_id,costprice");
												if($rsSell['rec_id']){
													$this->db->update("db_order_sell",array("costprice"=>$postdata["cosprice"])," rec_id='".$rsSell["rec_id"]."'");
													$text="工厂配件：".$rssellgoods["goods_sku"]." 原成本价:".$rsSell["costprice"]." 自动更新为:".$postdata["cosprice"];
													$this->fun->goods_update_log($rsOrder["order_id"],$text,3);	//更新成本价
												}
											}
									}
								}
							}


							if($key==0)
								$ks="";
							else
								$ks=",";
							$urlorder.=$ks.$order;
						}else{
							 $rsdbds = $this->fun->getdatabasesdetail("db_factory_order"," AND orderId='".$order."'");
							 $this->db->insert("db_factory_orderlog",array("orderId"=>$rsdbds["id"],"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>'重复完成（该订单已完成）',"spcodeid"=>1));
						}
					
					
				}
			}
			 $this->fun->phpalert(4, "", '', "/factory/orderlist?other=$urlorder");
		}
		if($op =='saveurgentorder')
		{
			$orderID = $this->input->post('id');
			$content ="";
			$memo = $this->input->post('memo');
			$orderlist =array_unique(array_filter(explode(",",$orderID)));
			foreach($orderlist as $key=>$rs)
			{
				 $rsdbds = $this->fun->getdatabasesdetail("db_factory_order"," AND orderId='".$rs."' AND updateflag=9 ");
				 if($rsdbds){
				    $this->db->update('db_factory_order',array("orderurgent"=>'17',"nature"=>$memo),"orderId='".$rs."'");//优先发货订单
					$text = "优先处理->".$memo;
					$rsdb = $this->fun->getdatabasesdetail("db_factory_order"," AND orderId='".$rs."'");
					$this->db->insert("db_factory_orderlog",array("orderId"=>$rsdb["id"],"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>$text,"spcodeid"=>1));
				}else{
					$msg['code'] = 201;
					$msg['txt'] = $rs."没有派单，不允许申请优先处理";
					echo json_encode($msg);
					die;
				}
			}
			$order = substr($this->input->post('id'),0,-1);
			$msg['code'] = 200;
			$msg['txt'] = $order;
			echo json_encode($msg);
			die;
		}
		if($op =='saveurgentordertip')
		{
			$orderID = $this->input->post('id');
			$types = $this->input->post('t');
			$memo = $this->input->post('memo');
				
			$orderlist =array_unique(array_filter(explode(",",$orderID)));
			foreach($orderlist as $key=>$rs)
			{
					
				$rsdb = $this->fun->getdatabasesdetail("db_factory_order"," AND orderId='".$rs."'");
				if($types==1)
				{
					$this->db->update('db_factory_order',array("orderurgenttip"=>'1',"orderurgent"=>'18'),"orderId='".$rs."'");//优先发货订单
					$text = "通过审核加急处理";
					$this->db->update("db_factory_order",array("updateflag"=>9)," orderId='".$rs."'");//标识该订单被派单了。工厂显示新订单！销售显示派单
				}else{
					$this->db->update('db_factory_order',array("orderurgenttip"=>'2',"orderurgent"=>'18'),"orderId='".$rs."'");//优先发货订单
					$text = "不通过加急处理审核->".$memo;

					//消息提醒
					$randid = $this->message->getMessageNums();	
					$firsttrial ="";
					
					$firstt=$this->db->get_one("SELECT * FROM db_factory_orderlog WHERE orderId='".$rsdb['id']."' AND (descr like '%有在途派单申请理由%' or descr like '%优先处理%') order by id desc");
					$firsttrial[]= $firstt["opername"];
					array_push($firsttrial,$rsdb['responsible']);
					$firsttrial = array_unique($firsttrial);
					foreach($firsttrial as $rsst)
					{
						$postMessageData["message_type"] = $this->message->getMessageType(10);	//新创建
						$message= $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."工厂订单{$rsdb[orderId]}优先处理被驳回,原因 {$memo}";
						$postMessageData["message"] = $message;
						$postMessageData["message_toName"] = $rsst;
						$postMessageData["url"] = '/factory/orderdetail?id='.$rsdb['id'];
						$postMessageData["isread"] =  $randid;
						$this->fun->saveMessage($postMessageData);
					}

				}
				
				$this->db->insert("db_factory_orderlog",array("orderId"=>$rsdb["id"],"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>$text,"spcodeid"=>1));
			}
			$order = substr($this->input->post('id'),0,-1);
			$msg['code'] = 200;
			$msg['txt'] = $order;
			echo json_encode($msg);
			die;
		}
		if($op=='changstatus')
		{
			$orderID = $this->input->post('id');
			$status = intval($this->input->post('st'));
			$content ="";
			$orderlist =array_unique(array_filter(explode(",",$orderID)));

			foreach($orderlist as $key=>$rs)
			{
				$rsdb = $this->fun->getdatabasesdetail("db_factory_order"," AND orderId='".$rs."'");
				if($status==7)
				{
					if($rsdb["orderurgent"] =="17" || $rsdb["orderurgent"] =="18" )
					{
					
					}else{
						$this->db->update('db_factory_order',array("orderurgent"=>'-5'),"orderId='".$rs."'");	//标加急
						$text = "批量标加急";
					}
				}elseif($status==6)
				{
					$this->db->update('db_factory_order',array("orderurgent"=>'-4',"updateflag"=>'9'),"orderId='".$rs."'");	//禁止发货
					$text = "批量标禁止发货";
				}elseif($status==16)
				{
					$this->db->update('db_factory_order',array("orderurgent"=>'0'),"orderId='".$rs."'");//取消禁止发货 、 取消加急
					$text = "批量标取消加急、禁止发货";
				}else{
					if($status==3)
					{
						$this->db->update('db_factory_order',array("status"=>$status,"finshtime"=>date("Y-m-d H:i:s")),"orderId='".$rs."'");	//标完成，并记录完成时间
						$text = "批量标完成";
					}elseif($status==4)
					{
						$this->db->update('db_factory_order',array("status"=>$status,"shopmenttime"=>date("Y-m-d H:i:s")),"orderId='".$rs."'");//标发货，并记录发货时间
						$text = "批量标发货";
					}else{
						if($status==5){
							//判断当前用户是否为销售在操作 当前销售对生产完成进行作废操作
							$userclassid = $_COOKIE['classid'];
							if(in_array($userclassid,array(2,3,4,5))&&$rsdb['status']==3){ //3为生产完成状态
								$this->db->update('db_factory_order',array('cancel_flag'=>1),"orderId='".$rs."'");	//标作废
								$text = "销售批量申请作废状态";
							}else{
								//如果是标作废，有五位关联的自动修改成五位关联！
								$isback = $this->fun->backupfactorylinkproduct($rs);//还原订单五位SKU信息
								$rval="";
								if($isback != false)
								{
									if($isback['code'] == 201)
									{
										$order = $this->fun->getdatabasesdetail("db_order_list"," AND order_sn = '".$isback['tradeid']."'");
										$sell = $this->fun->getdatabasesdetail("db_order_sell"," AND order_id = '".$order['order_id']."' AND goods_sn='".$isback['sku']."'");
										if($sell){
											$rval= "工厂订单[{$isback[factory_order_id]}]作废，订单[{$isback[tradeid]}]原SKU【{$sell[goods_sn]}】修改为：$isback[linksku],关联价：$isback[costprice]<br>";
											$this->fun->goods_update_log($order['order_id'], $rval, 3);    //日志
											$content.=$rval;


											/****如果是8位定制SKU转五位，提醒仓库******/
											if($this->fun->getfactorygoodsku($sell['goods_sn']))
											{
												//给仓库人员发送消息
												$randid = $this->message->getMessageNums();	//获取当前存储的条数
												$receivers_config = trim($this->config->item('sys_cang_tipsmessage'));
												$arr_receiver_config = explode("|",$receivers_config);
												foreach($arr_receiver_config as $rs)
												{
													$postMessageData["message_type"] = $this->message->getMessageType(0);	//消息提醒
													$crval = $rval." 物流方式：".$order['shipping_name'];
													$message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"." {$crval}";
													$postMessageData["message"] = $message;
													$postMessageData["message_toName"] = $rs;
													$postMessageData["isread"] =  $randid;
													$postMessageData["url"] = '/orderlist/editorder?order_id='.$sell["order_id"];
													$this->fun->saveMessage($postMessageData);
												}
											}


											//还要修改下关联成本

											$this->db->update('db_order_sell',array("goods_sn"=>$isback['linksku'],"goods_id"=>$isback['goods_id'],"costprice"=>$isback['costprice'])," rec_id=".$sell['rec_id']);

										}
									}
								}else{
									$rsdbSell = $this->fun->getdatabasesdetail('db_factory_sell'," AND orderId='".$rsdb['id']."'");
									$content.= "工厂订单[{$rsdb[orderId]}]作废，订单[{$rsdb[mabangorderid]}] 店铺[{$rsdb[shopId]}] SKU【{$rsdbSell[goods_sku]}】<br>";
								}



							}

						}

						//判断当前用户是否为销售在操作
						$userclassid = $_COOKIE['classid'];
						if($status==5&&in_array($userclassid,array(2,3,4,5))&&$rsdb['status']==3){ //3为生产完成状态
							//$this->db->update('db_factory_order',array('cancel_flag'=>1),"orderId='".$rs."'");	//标作废
						}else{
							$this->db->update('db_factory_order',array("status"=>$status,"updateflag"=>'9'),"orderId='".$rs."'");	//标作废
							$text = "批量修改状态";
						}

						//$this->db->update('db_factory_order',array("status"=>$status,"updateflag"=>'9'),"orderId='".$rs."'");	//标作废

					}
				}
				if($text){
				 $this->db->insert("db_factory_orderlog",array("orderId"=>$rsdb["id"],"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>$text,"spcodeid"=>1));
				}
			}
			if($content)
			{
				$msg['code'] = 201;
				$msg['txt'] = $content;
				$order = substr($this->input->post('id'),0,-1);
				$msg['url'] = $order;
				
			}else{
				$order = substr($this->input->post('id'),0,-1);
				$msg['code'] = 200;
				$msg['txt'] = $order;
			}
			echo json_encode($msg);
			die;
		}

		if($op == "getprice")
		{
			$rsdb = $this->fun->getdatabasesdetail("db_factory_order A left join db_factory_sell B on A.id = B.orderId LEFT JOIN db_goods C on B.goods_sku =C.goods_sku"," AND A.orderId = '".$this->input->post('orderid')."'","wages,A.status,B.custom,C.g_costprice,C.goods_sku,A.factoryId");
			if($rsdb)
			{
			  switch ($rsdb["status"]) {
                case 1;
                    $rsdb["statustext"] = '新订单';
					break;
				case 2:
					$rsdb["statustext"] = '生产中';
					break;
				case 3:
					$rsdb["statustext"] = '生产完成';
					break;
				case 4:
					$rsdb["statustext"] = '已发货';
					break;
				case 5:
					$rsdb["statustext"] = '作废单';
					break;
			 }
			
			$rsdb["isfactoryId"] ="";
			if($rsdb["factoryId"] ==1)
			{
				if($_COOKIE["classid"] ==13)	//工厂2人员
				{
					$rsdb["isfactoryId"] ="工1订单";
				}
			}

			if($rsdb["factoryId"] ==2)
			{
				if($_COOKIE["classid"] ==12)	//工厂1人员
				{
					$rsdb["isfactoryId"] ="工2订单";
				}
			}
				

				echo json_encode($rsdb);
				die;
			}else{
				$rsdb = array("wages"=>"err");
				echo json_encode($rsdb);
				die;
			}
		}
			
		if($op =='saveprintcode')
		{
			$type = $this->input->get('type');
			if($type=="")
			{
				die('选择订单号');
			}
			
			$num =1;
			$times = date("m/d");
			if($type)
			{
				$str="";
				$goods_sku = substr($type,0,-1);
				$goods_sku = explode(",",$goods_sku);
				foreach($goods_sku as $key=>$rs)
				{
						$str.='<div style=" width:75mm; height:20mm; margin-left:2.5mm;page-break-after:always;"><ul style="width:70mm; height:18mm; margin-left:2.5mm;"><li>';
						$str.=" <img src=\"/fuman/barcode/html/image.php?filetype=PNG&dpi=72&scale=2&rotation=0&font_family=0&font_size=8&text={$rs}&thickness=40&checksum=&code=BCGcode39\" > </li></ul>";
						$str.=' <ul style="width:70mm; height:2mm; margin-left:2.5mm;"> <li style="text-align:left; font-size:13px; font-weight:bold; width:44mm; overflow:hidden;white-space:nowrap; text-overflow:ellipsis;">';
						$str.=$goods_sku[$key];
						$str.=' </li><li style="text-align:left; font-size:12px;width:25mm;">'.$times;
						$str.="</li></ul>";
						
						$str.='</div>';
					
				}
				$this->tpl->assign("str", $str);
			$this->tpl->display("product/printcode.tpl",0,0,1);
			}
		}
		//批量标生产状态
		if($op=="producestatusorder"){
			$str_ids = trim($this->input->post("id"),",");
			$produce_status = trim($this->input->post('producestatus'));
			$caijian = trim($this->input->post("caijian"));
			$caijian_person = "SELECT * FROM d_user WHERE id = '{$caijian}' ";
			$rs_caijian = $this->db->query($caijian_person)->row_array();

			$cur_date = trim($this->input->post("cur_date"));
			$str_content = "";
			if($produce_status == 1 || $produce_status == 2){
				$data['person1'] = $caijian; //裁剪人员
				if($produce_status == 1){
					$str_content.= "裁剪中";
				}
				if($produce_status == 2){
					$str_content.= "裁剪完成";
				}
			}
			if($produce_status == 3 || $produce_status == 4){
				$data['proWorker'] = $caijian; //生产工人
				if($produce_status == 3){
					$str_content.= "制作中";
				}
				if($produce_status == 4){
					$str_content.= "制作完成";
				}
			}
			$arr_ids = explode(",",$str_ids);
			foreach($arr_ids as $k=>$v){
				$sql = "SELECT * FROM db_factory_order WHERE orderId = '{$v}' ";
				$rs  = $this->db->query($sql)->row_array();
				$this->db->update("db_factory_order",array("produce_status"=>$produce_status)," orderId = '".$v."'");
				$this->db->update("db_factory_sell",$data," orderId = '".$rs['id']."'");
				//日志信息
				$str = $str_content." ".$rs_caijian['name'];
				$this->db->insert("db_factory_orderlog",array("orderId"=>$rs["id"],"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>'批量修改生产状态 '.$str." ".$cur_date,"spcodeid"=>1));

			}
			echo 200;exit;

		}

		if($op == "updMaterialData"){
			$status = trim($this->input->post('status'));
			$id     = trim($this->input->post('id'));
			if($status==1){
				$this->db->delete("db_factory_material"," id = '".$id."'");
				echo 200;exit;
			}
			if($status==2){ //获取相关编辑数据
				$sql = "SELECT * FROM db_factory_material WHERE id = '{$id}' ";
				$rs  = $this->db->query($sql)->row_array();
				echo json_encode($rs);exit;
			}


		}
        if($op == "getorderForFactoryNumber"){
            $orderlist = trim($this->input->post('orderlist'));
			if($orderlist!=''){//有运单号
				$order_sn_list = explode("\n",trim($orderlist));
                $orderids=array();
				foreach($order_sn_list as $key=>$sn){
				    $sn=str_replace("\\r",'',$sn);
                    $factory_orderids[]=$sn;
				}
                $this->db->where_in('orderId',$factory_orderids);
                $this->db->where('isform',1);
                $forderlist = $this->db->get('db_factory_order')->result_array();  
                   //echo $this->db->last_query();       
                foreach($forderlist as $key=>$order){
					$orderids[]=$order['orderId'];
                    $order_sn_str.=$order["mabangorderid"].",";
				}
                echo $order_sn_str;
		    }
        }
		
		if($op == "showmabangorder")
		{
			$str = "";
			$orderid = $this->input->post('id');
			$Dhldeliver = $this->input->post('Dhldeliver');
		
			
			$express_type=array('sfexpress'=>1,'UPS'=>2,'DHL'=>3,'CNE'=>4,'UBI'=>5,'YT'=>6,'YW'=>7,'EMS'=>8,'WUY'=>9);
			$orderType=$express_type[$Dhldeliver];//交运方式
			if($orderid)
			{
				$order = explode("\n",$orderid);
				foreach($order as $s)
				{
					$rsdb = $this->fun->getdatabasesdetail("db_factory_order"," AND orderId = '".trim($s)."'","mabangorderid,isform");
					if($rsdb)
					{
						$mabangorderid = $rsdb["mabangorderid"];
						$isform		   = $rsdb["isform"];	//0来源马帮 1新系统
						if($isform == 1)
						{
							$newsysorder[] = $mabangorderid;	//新系统订单
						}else{
							$mabangorders[] = $mabangorderid;	//马帮订单
						}
					}
				}
			}

			if(count($mabangorders)>0)
			{
				$orderlist = implode("\n",$mabangorders);
				$this->load->library('Mabang');
                $res= $this->mabang->savemabangorderlist($orderlist,$Dhldeliver,$orderType); //燕文orderType 7
			}
			if(count($newsysorder)>0)
			{
				 $orderdata = implode("','",$newsysorder);
				 $this->m->saveexress($orderdata,$Dhldeliver,$orderType);
			}
			if($orderType==1)
			{
				header("location:/doit/sfexpress/0/0");
			}
			if($orderType==2)
			{
				header("location:/doit/ajaxbutton?op=upsexpress");
			}
			if($orderType==3)
			{
				header("location:/expressshipment/ajaxbutton?op=DHLexpress");
			}
		}
	


		if($op == "delpexpend")
		{
			$this->db->delete("db_expend",array("id"=>intval($this->input->get('id'))));
			header("location:/factory/addexpend");
		}

		if($op == "getaddexpend")
		{
			$rsdb = $this->fun->getdatabasesdetail("db_expend"," AND id='".$this->input->post("id")."'");
			echo json_encode($rsdb);
			die;
		}

		

		if($op =="saveaddexpend")
		{
			$editid = $this->input->post('editid');
			
			$postdata="";
			$postdata["projeck"] = trim($this->input->post('projeck'));
			$postdata["type"] = trim($this->input->post('type'));
			$postdata["outmoney"] = trim($this->input->post('outmoney'));
			$postdata["outtime"] = trim($this->input->post('outtime'));
			$postdata["price"] = trim($this->input->post('price'));
			$postdata["num"] = trim($this->input->post('num'));
			$postdata["descr"] = trim($this->input->post('descr'));
			$postdata["supplier"] = trim($this->input->post('suppliersearch'));
			$postdata["factoryid"] = trim($_COOKIE["classid"]);
			$postdata["oper"] = trim($_COOKIE["username"]);
			$postdata["opertime"] =date("Y-m-d H:i:s");
			$postdata["expenddate"] =date("Y-m-d");
			$postdata["expendmoney"] =1;

			if($editid)
			{
			$this->db->update("db_expend",$postdata,"id=".$editid);
			}else{
			$this->db->insert("db_expend",$postdata);
			}

			echo 200;
			die;
		}

		if($op =='savematerial')
		{
			$editid = $this->input->post('material_id');
			$postdata="";
			$postdata["projeck"] = trim($this->input->post('projeck'));
			//类别
			$type= trim($this->input->post('type'));
			$typename = trim($this->input->post('typename'));
			$postdata["typename"] = $typename?$typename:$type;
			//供应商
			$supplier = trim($this->input->post('suppliersearch'));
			$suppliertwo= trim($this->input->post('supplier'));

			$postdata["supplier"] = $supplier?$supplier:$suppliertwo;
			$postdata["code"] = trim($this->input->post('code'));

			 $postdata["code"] = str_replace(" ", "", $postdata["code"]);


			$postdata["price"] = trim($this->input->post('price'));
			$postdata["num"] = trim($this->input->post('num'));
			$postdata["descr"] = trim($this->input->post('descr'));
			$postdata["factoryid"] = trim($_COOKIE["classid"]);
			$postdata["oper"] = trim($_COOKIE["username"]);
			$postdata["opertime"] =date("Y-m-d H:i:s");
			$postdata["dw"] = trim($this->input->post('dw'));
			
			$postdata["colores"] = trim($this->input->post('colores'));
			$postdata["cangwei"] = trim($this->input->post('cangwei'));
			if($editid){
				$sql = "SELECT * FROM db_factory_material WHERE id = '{$editid}' ";
				$rs  = $this->db->query($sql)->row_array();
				if(count($rs)>0){
					//修改相关物料信息
					$this->db->update('db_factory_material',$postdata," id=".$editid);

					$post="";
					$post['mater_code'] = $postdata["code"];
					$post['updatetime'] = date("Y-m-d H:i:s");
					$post['createUser'] = $_COOKIE["username"];
					$post["price"] = trim($this->input->post('price'));
					$post["pid"] = $editid;
					$post["num"] = trim($this->input->post('num'));
					$post['supplier'] = $supplier?$supplier:$suppliertwo;
					$post['typename'] = $typename?$typename:$type;


					$post['types'] = 3;
					$post['content'] ="原库数".$rs['num'].$rs['dw'].","."修改后库数".$this->input->post('num').trim($this->input->post('dw'));
					$post['old_data'] =$rs['num'];
					$post['new_data'] =$postdata["num"];

				}


			}else{
				//添加或更新数量
				$rsdb = $this->fun->getdatabasesdetail("db_factory_material"," AND code = '".$postdata['code']."'");
				if($rsdb)
				{
					$schedule = $this->input->post('num');
					$postdata['strlog'] = $rsdb["strlog"].";".$schedule;
					$postdata["num"] = trim($this->input->post('num'))+$rsdb['num'];
					$this->db->update("db_factory_material",$postdata,"id=".$rsdb['id']);


					$post="";
					$post['mater_code'] = $postdata["code"];
					$post['updatetime'] = date("Y-m-d H:i:s");
					$post['createUser'] = $_COOKIE["username"];
					$post['supplier'] = $supplier?$supplier:$suppliertwo;
					$post['typename'] = $typename?$typename:$type;
					$post["price"] = trim($this->input->post('price'));
					$post["pid"] = $rsdb['id'];
					$post['types'] = 1;
					$post["num"] = trim($this->input->post('num'));
					$post['content'] ="更新入库数".trim($this->input->post('num')).trim($this->input->post('dw'));
					$post['old_data'] =$rsdb["num"];
					$post['new_data'] =$postdata["num"];

				}else{
					$this->db->insert("db_factory_material",$postdata);
					$pid = $this->db->insert_id();
					$post="";
					$post['mater_code'] = $postdata["code"];
					$post['updatetime'] = date("Y-m-d H:i:s");
					$post['createUser'] = $_COOKIE["username"];
					$post["price"] = trim($this->input->post('price'));
					$post["pid"] = $pid;
					$post["num"] = trim($this->input->post('num'));
					$post['supplier'] = $supplier?$supplier:$suppliertwo;
					$post['typename'] = $typename?$typename:$type;


					$post['types'] = 1;
					$post['content'] ="新编入库数".$this->input->post('num').trim($this->input->post('dw'));
					$post['old_data'] =0;
					$post['new_data'] =$postdata["num"];
				}
			}

			

				$this->db->insert("db_factory_material_log",$post);

			
			echo 200;
			die;
		}
		if($op =='savematerchuk')
		{
			$code = trim($this->input->post('c_code'));
			$c_num = trim($this->input->post('c_num'));
			$c_memo = trim($this->input->post('c_memo'));
			$rsdb = $this->fun->getdatabasesdetail("db_factory_material"," AND code = '".$code."'");
			if($rsdb)
			{
					$post="";
					$post['num'] = $rsdb["num"]-$c_num;
					$post['strlog'] = $rsdb["strlog"].";".date("Y-m-d H:i:s")."减少".$post['num'];
					$this->db->update("db_factory_material",$post,"id=".$rsdb['id']);

					$post="";
					$post['mater_code'] = $rsdb["code"];
					$post['updatetime'] = date("Y-m-d H:i:s");
					$post['createUser'] = $_COOKIE["username"];
					$post['supplier'] = $rsdb['supplier'];
					$post['typename'] = $rsdb['typename'];
					$post["price"] = $rsdb['price'];
					$post["pid"] = $rsdb['id'];
					$post['types'] = 2;
					$post["num"] = trim($c_num);
					$post['content'] =$c_memo." 减少库存数->".$c_num.$rsdb["dw"];
					$post['old_data'] =$rsdb["num"];
					$post['new_data'] =$rsdb["num"]-$c_num;
					$this->db->insert("db_factory_material_log",$post);
			}
			echo 200;
			die;
		}
		if($op =='showmaterial')
		{

			
			$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		$where = " ";
		if($this->input->get_post('other'))
		{
			 $other =trim($this->input->get_post('other'));
			 $where.=" AND B.goods_sku = '".$other."'";
			 $this->tpl->assign("other",$other);
		}

		if($this->input->get_post('code'))
		{
			 $code =trim($this->input->get_post('code'));
			 $where.=" AND mater_code = '".$code."'";
		}

		
		$orderby = " order by id DESC";
		$list = $this->fun->getalllist("db_factory_material_log ", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
	
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("orderlist", $list["list"]);
			$this->tpl->display("factory/showmaterial.tpl");
		}
		if($op =='getmaterialcode')
		{
			$c_num = trim($this->input->post('c_num'));
			$rsdb = $this->fun->getdatabasesdetail("db_factory_material"," AND code = '".trim($this->input->post('c_code'))."'");
			if(!$rsdb)
			{
				echo 201;
				die;
			}
			if($rsdb["num"] <$c_num)
			{
				echo 202;
				die;
			}
		}
		if($op=='deletesanorder')
		{
			$this->db->delete("db_factory_scanorder","id=".intval($this->input->post('id')));
		}
		//工厂单件扫单
		if($op == 'batchfactoryExpress')
		{
			 $this->tpl->display("factory/batchfactoryExpress.tpl",0,0,1);
		}
		if($op =='ActionbatchfactoryExpress')
		{
			$orderid = trim($this->input->post('orderid'));
			$rsdb = $this->fun->getdatabasesdetail('db_factory_order'," AND orderId ='".$orderid."'");
			$resll =  $this->fun->getdatabasesdetail('db_factory_sell'," AND orderId ='".$rsdb["id"]."'");
			if(!$rsdb)
			{
				 echo json_encode(array("code"=>201,"txt"=>"{$orderid} 订单号不存在!"));
				 die;
			}
			if($_COOKIE["username"]=="")
			{
				 echo json_encode(array("code"=>201,"txt"=>"帐号被下线！请重新登录页面！再次打开扫单"));
				 die;
			}
			$order_id = $this->fun->getdatabasesdetail('db_factory_scanorder'," AND order_id ='".$rsdb["orderId"]."'");
			if($order_id)
			{
				 echo json_encode(array("code"=>201,"txt"=>"这个订单已经扫过！"));
				 die;
			}
			 switch ($rsdb["status"]) {
                case 1;
                    echo json_encode(array("code"=>201,"txt"=>"订单新订单状态"));
					die;
				case 2:
					 echo json_encode(array("code"=>201,"txt"=>"订单生产中状态"));
					 die;
				case 5:
					echo json_encode(array("code"=>201,"txt"=>"订单作废状态"));
					die;
			 }

			//根据规则显示运输方式
			$logistics = "";
			/**规则暂停使用
			$sql = "SELECT * FROM db_factory_scanrules WHERE status = 0 ORDER BY priority ASC ";
			$rs  = $this->db->query($sql)->result_array();
			if($rs){
				foreach($rs as $k=>$v){
					$rs_order = $this->fun->getdatabasesdetail('db_order_list'," AND order_sn ='".$rsdb['mabangorderid']."'".$v['sqlfilter']);
					if($rs_order){
						$days = (time()-strtotime($rs_order['ordertime']))/86400;
						$days = intval($days);
						$actionWeight = $resll['scale']*1000; //单位g
							if($v['weight1']){
								if($v['weight2']){
									if($days >= $v['days']&&$actionWeight>=$v['weight1']&&$actionWeight<=$v['weight2']){
										$logistics = $v['logistics'];
										break;
									}
								}else{
									if($days >= $v['days']&&$actionWeight>=$v['weight1']){
										$logistics = $v['logistics'];
										break;
									}
								}

							}else{
								if($v['weight2']){
									if($days >= $v['days']&&$actionWeight<=$v['weight2']){
										$logistics = $v['logistics'];
										break;
									}
								}else{
									if($days >= $v['days']){
										$logistics = $v['logistics'];
										break;
									}

								}

							}


					}
				}
			}**/
			$postst="";
			$postst["order_id"] = $rsdb["orderId"];
			$postst["goods_sku"] = $resll["goods_sku"];
			$postst["goods_id"] = $resll["skuID"];
			$postst["skuName"] = $resll["skuName"];

			$postst["goods_num"] = $resll["orderNum"]?$resll["orderNum"]:1;
			$postst["price"] = $resll["cosprice"];

			if($resll['custom']==1) $custom = "均码";
			if($resll['custom']==2) $custom = "定制";
			if($resll['custom']==3) $custom = "配件";
			$postst["specifications"] = $custom?$custom:"未填";
			$postst["factoryID"] = $rsdb["factoryId"];
			$factorylist =  $this->fun->getdatabasesdetail("db_factory"," AND id='".$rsdb["factoryId"]."'");
			$postst["factoryName"] = $factorylist["name"];
			$postst["insttime"] = date("Y-m-d");
			$postst["settlementtime"] = date("Y-m-d");
			$postst["oper"] = $_COOKIE["username"];
			$postst["type"] =1;
			$this->db->insert("db_factory_scanorder",$postst);

			//查询订单列表里面是否为多件
			$tradeorder = $this->fun->getdatabasesdetail('db_order_list'," AND order_sn = '{$rsdb['mabangorderid']}' AND tradeid ='".$rsdb['backdealid']."'");
			$sql_tradenum = "SELECT * FROM db_order_sell WHERE order_id = '{$tradeorder['order_id']}' ";
			$rs_tradenum  = $this->db->query($sql_tradenum)->result_array();

			$logistics = $tradeorder["shipping_name"];
			//检测订单状态
			$order_show_status = "";
			if(count($tradeorder)>0){
				if($tradeorder['order_status']==6){
					$order_show_status.= "作废 ";
				}
				if($tradeorder['is_nodelivery']==1){
					$order_show_status.= "禁止发货";
				}
				if($tradeorder['order_status']==5){
					$order_show_status.= "已完成";
				}
				if($tradeorder['order_status']==4){
					$order_show_status.= "已发货";
				}
				$order_show_status = "<span style='color:red;'>".$order_show_status."<br/></span>";
			}
			//订单多件的时候 检测是否为工厂和其他平台采购商品的混合体
			$goods_number = 0;
			foreach($rs_tradenum as $k=>$v){
				$goods_number = $goods_number + $v['goods_number'];
			}
			if($goods_number>1){

				$goods_num = 0;
				$message_c = ",外采购商品：<br/>";
				$stock = 0;
				foreach($rs_tradenum as $key=>$value){
					$goods_num = $goods_num + $value['goods_number'];
					$rsdb_goods = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku ='".$value['goods_sn']."'",'goods_parent_sku,goods_name,goods_id');
					$flag = substr($rsdb_goods['goods_parent_sku'],0,2);
					if(strlen($rsdb_goods['goods_parent_sku'])==8){
						if($flag=="11"||$flag=="12"){
							$rsdb_stock = $this->fun->getdatabasesdetail("db_goods_stock"," AND storage_id in(1,2) AND goods_id ='".$rsdb_goods['goods_id']."'",'sum(stock) as stock',"GROUP BY goods_id");
							if(count($rsdb_stock)>0){
								$stock = $stock+$rsdb_stock['stock'];
							}
						}else{
							$message .= $rsdb_goods['goods_name']."<br/>";
						}
					}else{
						$message .= $rsdb_goods['goods_name']."<br/>";
					}
				}
				$msg = "";
				$msg .= "共".$goods_num."件商品";
				//查询 有多少件工厂生产以及工厂生产多少件到货 getdatabaseslist
				$rsdb_factory = $this->fun->getdatabasesdetail("db_factory_order"," AND backdealid ='".$rsdb['backdealid']."'","GROUP_CONCAT(orderId) as orderIds ");
				$arr_factory_order = explode(",",$rsdb_factory['orderIds']);
				if(count($arr_factory_order)==$goods_num){
					$msg.= ",工厂定制";
					$rsdb_factory_scanorder = $this->fun->getdatabaseslist("db_factory_scanorder"," AND order_id in({$rsdb_factory['orderIds']}) ");
					$msg.= ",已到".count($rsdb_factory_scanorder)."件";
				}else{
					$rest_num = $goods_num-count($arr_factory_order);
					if(count($arr_factory_order)>0){
						$rsdb_factory_scanorder = $this->fun->getdatabaseslist("db_factory_scanorder"," AND order_id in({$rsdb_factory['orderIds']}) ");
						$msg.= ",工厂定制已到".count($rsdb_factory_scanorder)."件,";
						if($stock>0){
							$msg.= "与库存合发：".$stock;
						}
						//外采购商品：<br/>
					}
				}
				if($message){
					$message = $message_c.$message;
				}
				$msg.=$message;
			}else{
				$msg = "";
			}
		
			echo json_encode(array("code"=>200,"txt"=>"订单号：{$rsdb[orderId]} <br> SKU：{$resll[goods_sku]} <br> 名称：{$resll[skuName]} <br> 物流方式：{$logistics}  \r\n <br> 是否多件：<span style='color:red;'>{$msg}</span> \r\n<br> 订单状态：{$order_show_status}  \r\n"));
		
		}
		if($op == 'showscanorder')
		{
			$orderlist =  $this->fun->getdatabasesdetail("db_factory_scanorder"," AND id='". trim($this->input->post('id'))."'");
			echo json_encode($orderlist);
			die;
		}
		if($op =='savescanorder')
		{
			$goods =  $this->fun->getdatabasesdetail("db_goods"," AND goods_sku='". trim($this->input->post('goods_sku'))."'");
			$postst="";
			$postst["order_id"] = trim($this->input->post('order_id'));
			$postst["goods_sku"] = trim($this->input->post('goods_sku'));
			$postst["goods_id"] = $goods["goods_id"];
			$postst["skuName"] = $goods["goods_name"];
			$postst["goods_num"] = trim($this->input->post('goods_num'));
			$postst["price"] = $goods["bulkprice"];
			$postst["specifications"] =trim($this->input->post('specifications'));
			
			$fID = trim($this->input->post('fID'));
			if($fID==12)
			{
				$factorylistname = "工厂1";
				$factoryID = 1;
			}
			if($fID==13)
			{
				$factorylistname = "工厂2";
				$factoryID = 2;
			}
			$postst["factoryID"] = $factoryID;
			$postst["factoryName"] = $factorylistname;
			$postst["settlementtime"] = trim($this->input->post('insttime'));
			
			$postst["oper"] = $_COOKIE["username"];
			$postst["type"] =2;
			if($this->input->post('scanid')>0)
			{
				$this->db->update("db_factory_scanorder",$postst,"id='".$this->input->post('scanid')."'");
			}else{
				$postst["insttime"] = date("Y-m-d");
				$this->db->insert("db_factory_scanorder",$postst);
			}
			
			echo 200;
			die;
		}
		if($op =='printcontent')
		{
			$txt = $this->input->get('txt');
			echo $txt;
		}
		
		if($op =='getlinkproduct')
		{
			

			$model = $this->input->post('model');	//版型
			$gender1 = $this->input->post('gender1');//性别
			$size = $this->input->post('size');	//尺码
			$sku = $this->input->post('sku');	//SKU
			$type =  $this->input->post('type');//类型 1 输出关联SKU数组
			
			
			if($model == 1)
			{
				$model = "欧美";
			}
			if($model == 2)
			{
				$model = "亚洲";
			}

			if($gender1 == 1)
			{
				$sex = "男性";
			}
			if($gender1 == 2)
			{
				$sex = "女性";
			}
			if($gender1 == 3)
			{
				$sex = "9999";
			}
			if($size=='25') $sizestr = "XXS";
			if($size=='30') $sizestr = "XS";
			if($size=='35') $sizestr = "S";
			if($size=='40') $sizestr = "M";
			if($size=='45') $sizestr = "L";
			if($size=='50') $sizestr = "XL";
			if($size=='55') $sizestr = "XXL";
			if($size=='60') $sizestr = "XXXL";
			
			$goodslist = $this->fun->getdatabasesdetail("db_goods"," AND goods_parent_sku = '".$sku."' AND goods_sku !='".$sku."'","GROUP_CONCAT(goods_id) as goodsID");
		
			if($goodslist["goodsID"])
			{
				$goodsID = $goodslist["goodsID"];
				
				if($sex==9999)
				{
					$sexsql="";
				}else{
					$sexsql = "AND (attr_value='".$sex."' or attr_value='通用')";
				}
				$rsdb = $this->db->get_one("SELECT * from db_goods_attr where 1  $sexsql AND attr_id = 1 AND goods_id in (SELECT goods_id FROM db_goods_attr WHERE 1 AND goods_id in ($goodsID) AND (attr_value='".$sizestr."') AND attr_id = 2 ) and goods_id in (SELECT goods_id FROM db_goods_attr WHERE 1 AND goods_id in ($goodsID) AND (attr_value='".$model."') AND attr_id = 9 )");
			
				if($rsdb["goods_id"]){
					
					$attgoods = $rsdb["goods_id"];

					$Nrsdb = $this->fun->getdatabasesdetail("db_goods_attr"," AND goods_id ='".$attgoods."' AND (attr_value='".$sex."' or attr_value='通用') AND attr_id = 1");
					$modersdb = $this->fun->getdatabasesdetail("db_goods_attr"," AND goods_id ='".$attgoods."' AND (attr_value='".$model."' or attr_value='通用') AND attr_id = 9");
				
					if($Nrsdb && $modersdb)
					{
						
						$goodslistNUK = $this->fun->getdatabasesdetail("db_goods"," AND goods_id ='".$attgoods."'","goods_sku,goods_id");
						$msg['code'] = 201;
						$msg['linksku']  = $goodslistNUK["goods_sku"];
						$goods_ID_sku = $goodslistNUK["goods_id"];
						//获取在途信息
						$goods_stock = $this->fun->getdatabasesdetail("db_goods_stock"," AND goods_id ='".$goods_ID_sku."' and in_transit>0 AND storage_id in(1,2)","in_transit");
						if($goods_stock["in_transit"]>0)
						{
							$msg['in_transit']  = $goods_stock["in_transit"];
						}else{
							$msg['in_transit']  =0;
						}
						if($type==1)	//获取数组
						{
							$arraygoodsList = $this->db->select("goods_id,goods_sku")->get_where('db_goods',"goods_id in($goodsID)")->result_array();
							$msg['arraygoodsList']  = $arraygoodsList;
						}
						

						echo json_encode($msg);
						die;
						
						
					}else{
						echo 200;
						die;
					}
				}else{
					echo 200;
					die;
				}
			}else{
				echo 200;
					die;
			}
			
			
		
		}

		//成本价修改日志
		if($op =='costpricelog')
		{
			$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		
		$where = " AND types = 4";
		if($this->input->get_post('other'))
		{
			 $other =trim($this->input->get_post('other'));
			 $where.=" AND B.goods_sku = '".$other."'";
			 $this->tpl->assign("other",$other);
		}

		if($this->input->get('fID')==1)
		{
			$where .= " and  length(B.goods_parent_sku)=8 AND (locate(11,B.goods_parent_sku)=1 or locate(12,B.goods_parent_sku)=1 ) ";
		
		}elseif($this->input->get('fID')==2)
		{
			$where .= " and  length(B.goods_parent_sku)=8 AND (locate(11,B.goods_parent_sku)=1) ";
		}elseif($this->input->get('fID')==3)
		{
			$where .= " and  length(B.goods_parent_sku)=8 AND (locate(12,B.goods_parent_sku)=1) ";
		}elseif($this->input->get('fID')==4)
		{
				$where .= " and  length(B.goods_parent_sku) !=8 AND (locate(11,B.goods_parent_sku)!=1 or locate(12,B.goods_parent_sku)!=1 ) and length(B.goods_sku)<8 ";
		}
		 $this->tpl->assign("fID",$this->input->get('fID'));

		if($this->input->get('if_csv'))
		{
			$if_csv = 1;
		}
		$allprice = $allmoney = 0;
		$orderby = " order by A.id DESC";
		$where .= " and  B.goods_id >0 ";
		$list = $this->fun->getalllist("db_goods_log A LEFT JOIN db_goods B ON A.goods_id=B.goods_id ", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"A.*,B.goods_sku,B.goods_name,B.g_costprice,B.bulkprice,B.wages");
	
		//print_r($list["list"]);
	
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("allprice", $allprice);
		$this->tpl->assign("allmoney", $allmoney);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
		$this->tpl->assign("orderlist", $list["list"]);
		
			if($this->input->get('if_csv'))
			{
				$headers =array("商品编号","商品名称","原价格","修改后价格","备注","当前成本价","修改时间","操作人");
				foreach($list["list"] as $key=>$rs)
				{
					$listdata[$key][] = $rs["goods_sku"]; 
					$listdata[$key][] = $rs["goods_name"]; 
					$listdata[$key][] = $rs["old_data"];
					$listdata[$key][] = $rs["new_data"]; 
					$listdata[$key][] = $rs["content"]; 
					$listdata[$key][] = $rs["g_costprice"]; 
					$listdata[$key][] = $rs["updatetime"]; 
					$listdata[$key][] = $rs["createUser"]; 
				}
				$this->fun->ouputexclePro($headers,$listdata);
			}

			$this->tpl->display("factory/cospricelog.tpl");
		}
		/******保存JQ传回的Images信息************/
		if($op =='saveProductImages')
		{
			$id = $this->buy_m->saveProductImages($type=1);
			$sql = "SELECT * FROM db_factory_material WHERE id = {$id} ";
			$rs  = $this->db->query($sql)->row_array();
			$this->fun->phpalert(4, "", '', "/factory/material?other={$rs['code']}");
		}
        if($op == 'goodsReceiptList'){//收货对帐列表
          $this->goodsReceiptList();
        }
        
        if($op=='sendGoodsCheckForm'){
            $this->sendGoodsCheckForm();    
        }
        
        if($op=='sendGoodsCheck'){
            $this->sendGoodsCheck();
        }
        
        if($op=='sendGoodsCheckDetail'){
            $this->sendGoodsCheckDetail();
        }
        
        if($op=='sendGoodsCheckSave'){
            $this->sendGoodsCheckSave();
        }
        if($op=='delReciveCheckInfo'){
            $this->delReciveCheckInfo();
        }
        if($op=='goodsReciveCount'){
            $this->goodsReciveCount();
        }
		if($op == "applypricelist"){
			$nowpage = $_REQUEST["pageid"];
			if ($nowpage == "") $nowpage = 1;
			/*只计算2017-5-24号之后的订单信息**/
			$where = " AND B.status = 3 AND B.finshtime>='2017-05-24 00:00:00'";

			$where.= " AND A.statuses = 1 ";
			if($_COOKIE["classid"] ==12)	//工厂1人员
			{
				$where.=" AND B.factoryId = 1";
			}
			if($_COOKIE["classid"] ==13)	//工厂2人员
			{
				$where.=" AND B.factoryId = 2";
			}
			if($this->input->get_post('fID'))
			{
				$where.=" AND B.factoryId = '". trim($this->input->get_post('fID'))."'";
				$this->tpl->assign("fID", trim($this->input->get_post('fID')));
			}
			if($this->input->get_post('ls'))
			{
				$ls = trim($this->input->get_post('ls'));
				if($ls==1)	//负利润率
				{
					$where.=" AND A.rate < 0";
				}
				if($ls==2)	//利润率0-0.1
				{
					$where.=" AND A.rate < 0.1 AND A.rate >0";
				}
				if($ls==3)	//利润率无穷
				{
					$where.=" AND A.rate > 0";
				}

				$this->tpl->assign("ls",$ls);
			}

			if($this->input->get_post('other'))
			{
				$other =trim($this->input->get_post('other'));
				$where.=" AND A.goods_sku = '".$other."'";
				$this->tpl->assign("other",$other);
			}
			$status = trim($this->input->get_post("status"));
			if($status){
				$where.= " AND A.statuses = '".$status."'";
				$this->tpl->assign("status",$status);
			}
			if($this->input->get_post('lv'))
			{
				$lv =trim($this->input->get_post('lv'));
				$where.=" AND A.rate <= $lv";
				$this->tpl->assign("lv",$lv);
			}

			$starttime = trim($this->input->get('starttime'));
			if ($starttime) {
				$times = $starttime . " 00:00:00";
				$where .= " AND (orderTime >= '" . $times . "')";
				$this->tpl->assign("starttime", $starttime);
			}

			$endtime = trim($this->input->get('endtime'));
			if ($endtime) {
				$times = $endtime . " 23:59:59";
				$where .= " AND (orderTime <= '" . $times. "')";
				$this->tpl->assign("endtime", $endtime);
			}

			$o_starttime = trim($this->input->get('o_starttime'));
			if ($o_starttime) {
				$times = $o_starttime . " 00:00:00";
				$where .= " AND (finshtime >= '" . $times . "')";
				$this->tpl->assign("o_starttime", $o_starttime);
			}

			$o_endtime = trim($this->input->get('o_endtime'));
			if ($o_endtime) {
				$times = $o_endtime . " 23:59:59";
				$where .= " AND (finshtime <= '" . $times. "')";
				$this->tpl->assign("o_endtime", $o_endtime);
			}

			$allprice = $allmoney = 0;
			$where.= " GROUP BY A.goods_sku ";
			$orderby = " ORDER BY A.id ASC ";
			$list = $this->fun->getalllist("db_factory_sell A LEFT JOIN db_factory_order B ON A.orderId=B.id LEFT JOIN db_goods C ON A.goods_sku= C.goods_sku", $where, $nowpage, $if_csv, $this->pageSize, $orderby,"A.*,B.orderId as ordernumber,B.finshtime,B.money,B.orderTime,B.shopmenttime,B.mabangorderid,B.factoryId,B.country,C.g_costprice,C.goods_name,C.goods_id");
			//echo $this->db->last_query();exit;
			foreach($list["list"] as $key=>$rs)
			{
				if($rs["country"]=='china')
				{
					$list["list"][$key]["shipingfee"] = $shipingfee= 20;
				}else{
					$list["list"][$key]["shipingfee"] = $shipingfee= $rs["scale"] * 100;
				}

				$factorylist =  $this->fun->getdatabasesdetail("db_factory"," AND id='".$rs["factoryId"]."'");
				$list["list"][$key]["factoryl"]  = $factorylist["name"];

				if($rs["custom"] == 3)	//定制配件，不能以整套的价格
				{
					if($rs["cosprice"] ==0)
					{
						$g_costprice = $rs["g_costprice"];
					}else{
						$g_costprice = $rs["cosprice"];
					}

				}else{
					$g_costprice = $rs["g_costprice"];
				}

				$list["list"][$key]["g_costprice"] =$g_costprice;

				//如果是多个商品，金额只能以单个商品售价
				$orderList = $this->fun->getdatabasesdetail('db_order_sell A left JOIN db_order_list B on A.order_id = B.order_id'," AND B.order_sn = '".$rs["mabangorderid"]."'","count(rec_id) as id");
				if($orderList["id"]>1)
				{
					$moneys = $this->fun->getdatabasesdetail('db_order_sell A left JOIN db_order_list B on A.order_id = B.order_id'," AND B.order_sn = '".$rs["mabangorderid"]."' and A.goods_sn='".$rs["goods_sku"]."'","A.goods_amount");
					if($moneys["goods_amount"]){
						$rs["money"] = $moneys["goods_amount"];
					}
				}
				//利润率计算
				if($rs["money"]>0){
					$amount =($rs["money"]*0.835) - $shipingfee;
					if($amount !=0){

						$lv = ($amount - $g_costprice) / $amount;
						$list["list"][$key]["lv"]  = round($lv,3);
					}else{
						$list["list"][$key]["lv"]  = 0;
					}
				}else{
					$list["list"][$key]["lv"]  = 0;
				}
				$list["list"][$key]["money"] = $rs["money"];
				//判断是否有修改过成本价
				$loglist = $this->fun->getdatabasesdetail("db_goods_log"," AND goods_id='".$rs["goods_id"]."' AND types = 4" ,'*', " order by id DESC");
				if($loglist){
					$list["list"][$key]["loglist"]  = $loglist["content"];
				}
			}
			$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
			$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
			$this->tpl->assign("total", $list["total"]);
			$this->tpl->assign("allprice", $allprice);
			$this->tpl->assign("allmoney", $allmoney);
			$this->tpl->assign("pageList", $pageList);
			$this->tpl->assign("factorylist", $this->fun->getdatabaseslist("db_factory"));//工厂列表
			$this->tpl->assign("orderlist", $list["list"]);

			$this->tpl->display("factory/applypricelist.tpl");
		}

	}
    
    public function goodsReceiptList(){
        $search_data=$this->input->get();
        
        $starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        if(!empty($search_data['starttime']) || !empty($search_data['endtime'])){
            $where=$endtime!=''?"&& check_day between '".$starttime."' and '".$endtime."'":"&& check_day='".$starttime."'";  
        }
        if(in_array($_COOKIE["classid"],array(12,13,14)) && empty($search_data['factory'])){//12工厂1或 13工厂2人员只能看到指定工厂
            $factory_attr=array('12'=>'工厂1','13'=>'工厂2','14'=>'外部开发');
            $search_data['factory']=$factory_attr[$_COOKIE["classid"]];
            $this->tpl->assign('findfactory','none');
        }
        if(!empty($search_data['factory'])){
            $where.=" && factory ='".$search_data['factory']."'";  
        }
        $tpl_data=array('factory'=>$search_data['factory'],'endtime'=>$endtime,'starttime'=>$starttime);
		$list = $this->fun->getalllist("db_factory_recive_check", $where, $nowpage, $if_csv, $this->pageSize," order by check_day desc",'*');
        
        $this->tpl->assign($tpl_data);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);
        $this->tpl->display("factory/goodsReceiptList.tpl");
    }
    
    public function sendGoodsCheckForm(){
        $selectMonth=array();
        for($i=0;$i>-45;$i--){
            $selectMonth[]= date("Y-m-d",strtotime($i." day"));
            //echo "<br />";    
        }
        $department=$_COOKIE['department'];
         $this->tpl->assign("department", $department);
        $this->tpl->assign("selectMonth", $selectMonth);
        $this->tpl->assign("deliverType", $deliver_type);
        $this->tpl->display("factory/sendGoodsCheckForm.tpl");
    }
    
    public function sendGoodsCheck(){
        require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
        set_time_limit(0);
        $check_day=$this->input->post("selectday");
        $deliverType=$this->input->post("deliverType");
        
        if(!$check_day){
            echo "必须选择出货单的出货时间";exit;
        }
        $factory_type_val=2;
        $factory_type=array(1=>"工厂1",2=>'工厂2');
        $arr_excel_file = $_FILES['file_excel'];
        if(!empty($arr_excel_file) && $arr_excel_file['error']==0) {
            $fileName = $arr_excel_file["name"];
            $tmpFileName = $arr_excel_file["tmp_name"];
            $fileExtName = explode(".", $fileName);
            if (!($fileExtName[1] == "xls" || $fileExtName[1] == "xlsx")) {//扩展名判断
                echo "上传的文件扩展名应该为.xls或.xlsx";
                exit;
            }
            if ($fileExtName[1] == 'xlsx') {
                $objReader = new PHPExcel_Reader_Excel2007();
                $objExcel = $objReader->load($tmpFileName);
            } else if ($fileExtName[1] == 'xls') {
                $objReader = new PHPExcel_Reader_Excel5();
                $objExcel = $objReader->load($tmpFileName);
            }
           // $this->repeatCheck();
            
            $result=$this->m->checkExpPriec($objExcel,$factory_type_val);
            foreach($result as $key=>$val){
                $result[$key]['recive_date']=$check_day;
            }   

  
            $order_numbers=iarray_column($result,'order_number');
            $skulist=iarray_column($result,'sku');
            if(count($skulist)>0){
                $skulist_str=implode("','",$skulist);
                $costprice_where=" && goods_sku in('$skulist_str')";
            }
            
            foreach($result as $key=>$val){
                if($val['data_type']==2){
                    $once_orderids[]=$val['order_number'];                
                }
            }
            if(count($once_orderids)>1){
                $once_orderid_str=implode(',',$once_orderids); 
                $once_where=" or  order_id in($once_orderid_str)";  
            }
            
            $costprices=$this->fun->getdatabaseslist("db_goods", $costprice_where,'goods_sku,g_costprice,bulkprice');
            $costprice_arr=iarray_column($costprices,'g_costprice','goods_sku');
            $bulkprice_arr=iarray_column($costprices,'bulkprice','goods_sku');//关联批量价
            if(count($order_numbers)>0){
                $order_numbers_str=implode(',',$order_numbers);
                $recive_where=" && order_id in($order_numbers_str) && settlementtime='$check_day' $once_where";
            }
            $recive_list=$this->fun->getdatabaseslist("db_factory_scanorder", $recive_where);
            //echo $this->db->last_query();
            $have_list=$have_arr=$recive_orderids=$check_arr=array();
            foreach($recive_list as $key=>$val){
                $info=$val['order_id']."_".$val['goods_sku']."_"."{$val[specifications]}";
                if($val['type']==2){
                    $sizeinfo=explode(',',$val['specifications']);//L,亚洲,男
                    $suffix2=$val['order_id']."_".$val['goods_sku']."_".$sizeinfo[0].",".$sizeinfo[2];
                    $have_list[$suffix2]=$val;
                }
                 
                $have_list[$info]=$val;
                $recive_orderids[]=$val['order_id'];
                $check_arr[$val['order_id']]['skus'][]=$val['goods_sku'];
                $check_arr[$val['order_id']]['styles'][]=$val['specifications'];
            }
            
            $check_list=$err_arr=$waring_arr=array();
            $total_num=$total_price=$factory_price=$factory_num=0;
            foreach($result as $key=>$val){
                
                $val['size']=trim($val['size']);
                $val['style']=trim($val['style']);
                $val['sex']=trim($val['sex']);
          
                if($val['data_type']==1){
                    $specifications="{$val[size]},{$val[style]},{$val[sex]}";
                    $info=$val['order_number']."_".$val['sku']."_"."{$val[size]},{$val[style]},{$val[sex]}";  //XL,欧美,女
                    $suffix2=$val['order_number']."_".$val['sku']."_".$val['size'].",".$val['sex'];
                    $val['costprice']=$bulkprice_arr[$val['sku']]>0?$bulkprice_arr[$val['sku']]:0;
                    $info=$have_list[$info]['goods_num']>0?$info:$suffix2;
                    $have_list[$info]['goods_num']=$have_list[$info]['goods_num']>0?$have_list[$info]['goods_num']:0;
                    $val['goods_num']=$have_list[$info]['goods_num'];
                
                    $double_nums+=$val['goods_num'];
                    $double_factory_nums+=$val['numbers'];
                    $double_prices+=$val['costprice']*$val['goods_num'];
                    $double_factory_prices+=$val['costprice']*$val['numbers'];
                }else{
                    $suffix2='';
                    $specifications="{$val[size]}";
                    $info=$val['order_number']."_".$val['sku']."_"."{$val[size]}";   
                    $val['costprice']=$costprice_arr[$val['sku']]>0?$costprice_arr[$val['sku']]:0; //
                    $val['goods_num']=$have_list[$info]['goods_num'];
                    $once_nums+=$val['goods_num'];
                    $once_factory_nums+=$val['numbers'];
                    $once_prices+=$val['costprice']*$val['goods_num'];
                }
                
                $val['specifications']=$specifications;
                $info=$have_list[$info]['goods_num']>0?$info:$suffix2;
                $have_list[$info]['goods_num']=$have_list[$info]['goods_num']>0?$have_list[$info]['goods_num']:0;
                $val['goods_num']=$have_list[$info]['goods_num'];
                if(in_array($val['order_number'],$recive_orderids)){//订单id是否存在
                    $total_num+=$have_list[$info]['goods_num'];
                    $total_price+=$val['costprice']*$have_list[$info]['goods_num'];
                    $factory_price+=$val['costprice']*$val['numbers'];
                    $factory_num+=$val['numbers'];
                    if(!in_array($val['sku'],$check_arr[$val['order_number']]['skus'])){
                        echo $info;
                        $val['skuerror']='1';
                    }
                    if(!in_array($val['specifications'],$check_arr[$val['order_number']]['styles']) && $have_list[$info]['goods_num']<1){
                        $val['styleerror']='1';
                    }
                    if($have_list[$info]['goods_num']==$val['numbers']){
                        $val['checkstatus']='success'; 
                        $check_list[]=$val;   
                    }else{
                        $val['checkstatus']='numbererror';
                        $val['numbererror']='1';
                        $waring_arr[]=$val;
                    }
                    
                }else{
                    $factory_price+=$val['costprice']*$val['numbers'];
                    $factory_num+=$val['numbers'];
                    $val['checkstatus']='nothave';
                    $val['orderiderror']='1';
                    $err_arr[]=$val;
                }
                
            }
            $error_datas=array_merge($err_arr,$waring_arr);
            $check_error_data_json=json_encode($error_datas);
            $check_data_list=array_merge($err_arr,$waring_arr,$check_list);
            $check_data_json=json_encode($check_data_list);
            $tpl_data=array('check_data_json'=>$check_data_json,'check_error_data_json'=>$check_error_data_json,
            'check_day'=>$check_day,'total_num'=>$total_num,'total_price'=>$total_price,
                'factory_price'=>$factory_price,'factory_num'=>$factory_num,'factory'=>$_POST['factory'],'totalinfo'=>array(
                $double_nums,$double_prices,$double_factory_nums,$once_nums,$once_prices,$once_factory_nums,$double_factory_prices));
            $web_title=$_POST['factory']."出货与收货扫件对帐结果";
            $this->tpl->assign('web_title',$web_title);
            $this->tpl->assign('chargeslist',$check_data_list);
            $this->tpl->assign($tpl_data);
            $this->tpl->display('factory/sendGoodsCheck.tpl');//orderlist/chargeslist.tpl
        }else{
            echo '请上传需要对帐的帐目文件';
        }
    }
    
    //出货与入库合计
    public function goodsReciveCount11(){
        echo '<div align="center"><strong>对帐合计功能不够完善，目前修复中，预计3月22号下午1左右正常</strong></div>';
    	$starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-01"):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $factoryid=$_GET['factory'];
        $repeat_check_where=" && recive_date >='$starttime' && recive_date<='$endtime'";
        
        if(in_array($_COOKIE["classid"],array(12,13,14))){//12工厂1或 13工厂2人员只能看到指定工厂
            $factory_attr=array('12'=>'工厂1','13'=>'工厂2','14'=>'外部开发');
            $factoryid=$factory_attr[$_COOKIE["classid"]];
            $this->tpl->assign('findfactory','none');
        }
        if(!empty($factoryid)){
            $repeat_check_where.=" && factory='$factoryid'";
        }
        $warning_list=$this->fun->getdatabaseslist("db_factory_check_warning", $repeat_check_where);
        $all_data=$sku_orders=array();
        foreach($warning_list as $key=>$rs){
            $check_data=json_decode($rs['warning_data'],true);
            foreach($check_data as $i=>$val){
                $check_data[$i]['factory']=$val['factory']=$rs['factory'];
                //$all_data[]=$val;
                $sku_orders[$val['order_number']."_".$val['sku']."_".$val['specifications']]=$val;
            }
        }
        foreach($sku_orders as $key=>$val){
            $check_orders[]=$key;
        }
        $send_goods_where=" && check_day >='$starttime' && check_day<='$endtime'";
        $send_goods=$repeat_check_data=$this->fun->getdatabaseslist("db_factory_recive_check", $send_goods_where);
        $check_data_ids=array();
        foreach($send_goods as $key=>$info){
            $check_data=json_decode($info['check_data_json'],true);
            foreach($check_data as $i=>$val){
                if(in_array($val['order_number']."_".$val['sku']."_".$val['specifications'],$check_orders)){
                    $sku_orders[$val['order_number']."_".$val['sku']."_".$val['specifications']]['send_count']+=$val['numbers'];
                    $need_up_ids[$val['order_number']."_".$val['sku']."_".$val['specifications']][]=$info['id'];         
                }  
            }
               
        }
        dump($need_up_ids);
        die;
        if(count($sku_orders)>0){
            foreach($sku_orders as $key=>$val){
                $recive_where_str.="or(order_id=$val[order_number] && goods_sku='$val[sku]' && specifications='$val[specifications]')";
            }
            $recive_where_str=" && (".trim($recive_where_str,'or').")";
            $recive_where_str.=" && settlementtime>='$starttime' && settlementtime<='$endtime'";
            $fuman_recives=$this->fun->getdatabaseslist("db_factory_scanorder", $recive_where_str,'order_id,type,goods_sku,
            goods_num,settlementtime,specifications');
            foreach($fuman_recives as $key=>$val){
                $sku_orders[$val['order_id']."_".$val['goods_sku']."_".$val['specifications']]['recive_count']+=$val['goods_num'];    
            }
            foreach($sku_orders as $key=>$rs){
                $rs['recive_count']=$rs['recive_count']==''?0:$rs['recive_count'];
                $rs['diff_count']=$rs['send_count']-$rs['recive_count'];
                $sku_orders[$key]=$rs;
                if($rs['diff_count']==0){
                    //$check_data  
                    $this->clearErrorStatus($need_up_ids[$key],$key);
                }
            }
        }
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'list'=>$sku_orders);
        $this->tpl->assign($tpl_data);
        $this->tpl->display('factory/goodsReciveCount.tpl');    
    }


//出货与入库合计
    public function goodsReciveCount(){
    	$starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-01"):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
        $factoryid=$_GET['factory'];
        $repeat_check_where=" && recive_date >='$starttime' && recive_date<='$endtime'";
        
        if(in_array($_COOKIE["classid"],array(12,13))){//12工厂1或 13工厂2人员只能看到指定工厂
            $factory_attr=array('12'=>'工厂1','13'=>'工厂2');
            $factoryid=$factory_attr[$_COOKIE["classid"]];
            $this->tpl->assign('findfactory','none');
        }
        if(!empty($factoryid)){
            $repeat_check_where.=" && factory='$factoryid'";
        }
        $warning_list=$this->fun->getdatabaseslist("db_factory_check_warning", $repeat_check_where);
        $all_data=$sku_orders=array();
        foreach($warning_list as $key=>$rs){
            $check_data=json_decode($rs['warning_data'],true);
            foreach($check_data as $i=>$val){
                $check_data[$i]['factory']=$val['factory']=$rs['factory'];
                //$all_data[]=$val;
                $sku_orders[$val['order_number']."_".$val['sku']."_".$val['specifications']]=$val;
            }
        }
        $check_orders=array();
        foreach($sku_orders as $key=>$val){
            $check_orders[]=$key;
        }
        $send_goods_where=" && check_day >='$starttime' && check_day<='$endtime'";
        $send_goods=$repeat_check_data=$this->fun->getdatabaseslist("db_factory_recive_check", $send_goods_where);
        $check_data_ids=array();
        foreach($send_goods as $key=>$info){
            $check_data=json_decode($info['check_data_json'],true);
            foreach($check_data as $i=>$val){
                if(in_array($val['order_number']."_".$val['sku']."_".$val['specifications'],$check_orders)){
                    $sku_orders[$val['order_number']."_".$val['sku']."_".$val['specifications']]['send_count']+=$val['numbers'];
                    $need_up_ids[$val['order_number']."_".$val['sku']."_".$val['specifications']][]=$info['id'];         
                }  
            }
               
        }
        
        if(count($sku_orders)>0){
            foreach($sku_orders as $key=>$val){
                $recive_where_str.="or(order_id=$val[order_number] && goods_sku='$val[sku]' && specifications='$val[specifications]')";
            }
            $recive_where_str=" && (".trim($recive_where_str,'or').")";
            $recive_where_str.=" && settlementtime>='$starttime' && settlementtime<='$endtime'";
            $fuman_recives=$this->fun->getdatabaseslist("db_factory_scanorder", $recive_where_str,'order_id,type,goods_sku,
            goods_num,settlementtime,specifications');
            foreach($fuman_recives as $key=>$val){
                $sku_orders[$val['order_id']."_".$val['goods_sku']."_".$val['specifications']]['recive_count']+=$val['goods_num'];    
            }
            foreach($sku_orders as $key=>$rs){
                $rs['recive_count']=$rs['recive_count']==''?0:$rs['recive_count'];
                $rs['diff_count']=$rs['send_count']-$rs['recive_count'];
                $sku_orders[$key]=$rs;
                if($rs['diff_count']==0){
                    //$check_data  
                    $this->clearErrorStatus($need_up_ids[$key],$key);
                }
            }
        }
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'list'=>$sku_orders);
        $this->tpl->assign($tpl_data);
        $this->tpl->display('factory/goodsReciveCount.tpl');    
    }
    
    public function repeatCheck(){
        $recive_date=date("Y-m-d",strtotime('-15 day'));
        $repeat_check_where=" && createtime >='$recive_date'";
        $repeat_check_data=$this->fun->getdatabaseslist("db_factory_check_warning", $repeat_check_where);
        $warning_datas=array();
        foreach($repeat_check_data as $key=>$info){
            $warning_data=json_decode($info['warning_data'],true);
            foreach($warning_data as $i=>$rs){
                $rs['recive_date']=$info['recive_date'];
                $rs['check_id']=$info['check_id'];
                //unset($rs['checkstatus']);unset($rs['skuerror']);unset($rs['styleerror']);unset($rs['numbererror']);
                $warning_data[$i]=$rs;
            }
            $warning_datas=array_merge($warning_datas,$warning_data);
        }
            
        if(count($warning_datas)>0){
            $repeat_orderid=iarray_column($warning_datas,'order_number');
            $order_numbers_str=implode(',',$repeat_orderid);
            $repeat_have_where=" && order_id in($order_numbers_str)";
        }
        //dump($warning_datas);
        $recive_list=$this->fun->getdatabaseslist("db_factory_scanorder", $repeat_have_where,'order_id,type,goods_sku,
        goods_num,settlementtime,specifications');
        foreach($recive_list as $key=>$val){
            $sizeinfo=explode(',',$val['specifications']);
            if($val['type']==2){
                $new_arr[$val['order_id'].'_'.$val['goods_sku']."_".$sizeinfo[0]."_".$sizeinfo[2]][]=$val;   
            }else{
                $new_arr[$val['order_id'].'_'.$val['goods_sku']."_".$val['specifications']][]=$val;    
            }
            
        }
        $update_dates=array();
        foreach($warning_datas as $key=>$val){
            if($val['data_type']==1){
                $val['specifications']=$val['size']."_".$val['sex'];
            }
            if($new_arr[$val['order_number'].'_'.$val['sku']."_".$val['specifications']]){
                $infolist=$new_arr[$val['order_number'].'_'.$val['sku']."_".$val['specifications']];
                foreach($infolist as $i=>$rs){
                    $days=round(abs(strtotime($rs['settlementtime'])-strtotime($val['recive_date']))/86400);
                    if($days<=2 && $rs['goods_num']==$val['numbers'] && $rs['settlementtime']>$val['recive_date']){
                        $val['havedata']=$rs;
                        unset($val['checkstatus']);unset($val['skuerror']);unset($val['styleerror']);unset($val['numbererror']);
                        $update_dates[$val['check_id']][$val['id']]=$val;
                    }
                }
            }           
        }
       
        foreach($update_dates as $key=>$val){
            $real_checks=array();
            $order_numbers_str=implode(',',$repeat_orderid);
            $repeat_have_where=" && order_id in($order_numbers_str)";
            $checkinfo = $this->fun->getdatabasesdetail('db_factory_recive_check'," AND id=".$key);
	        $check_arr=json_decode($checkinfo['check_data_json'],true);
            foreach($check_arr as $i=>$rs){
                $new_check_val[$rs['id']]=$rs;
            }
            
            //删除异常的数据
            $wraning_data=$this->fun->getdatabasesdetail("db_factory_check_warning"," AND check_id=".$key);
            $wraning_datas=json_decode($wraning_data['warning_data'],true);
            foreach($wraning_datas as $i=>$rs){
                $new_wraning_val[$rs['id']]=$rs;
            }
            
            foreach($val as $index=>$info){
                if($info['data_type']==1){
                    $info['specifications']="{$info[size]},{$info[style]},{$info[sex]}";
                }
                $new_check_val[$info['id']]=$info;
                $total_num+=$info['numbers']-$info['goods_num'];
                $total_price+=($info['numbers']-$info['goods_num'])*$info['costprice'];
                $info['goods_num']=$info['havedata']['goods_num']; 
                unset($new_wraning_val[$info['id']]); 
            }
            $total_num=$checkinfo['total_num']+$total_num;
            $total_price=$checkinfo['total_price']+$total_price;
            
            
            $check_data_json=json_encode($new_check_val);
            $this->db->update('db_factory_recive_check',array('check_data_json'=>$check_data_json,
                'total_num'=>$total_num,'total_price'=>$total_price)," id=".$key);
            
            if(count($new_wraning_val)<=0){
                $this->db->delete('db_factory_check_warning'," AND check_id=".$key);    
            }else{
                $warning_data_json=json_encode($new_wraning_val);
                $this->db->update('db_factory_check_warning',array('warning_data'=>$warning_data_json)," check_id=".$key);  
            }
        }
    }
    
    public function clearErrorStatus($update_dates,$order_sku){
        $key=$order_sku;  
        foreach($update_dates as $i=>$check_data_id){
            $new_check_val=$new_wraning_val=array();
            $checkinfo = $this->fun->getdatabasesdetail('db_factory_recive_check'," AND id=".$check_data_id);
            //echo $this->db->last_query();
	        $check_arr=json_decode($checkinfo['check_data_json'],true);
            $check_arr=$check_arr==null?array():$check_arr;
            foreach($check_arr as $i=>$rs){
                if($new_check_val[$rs['order_number'].'_'.$rs['sku']."_".$rs['specifications']]['numbers']>0){
                    $rs['numbers']+=$new_check_val[$rs['order_number'].'_'.$rs['sku']."_".$rs['specifications']]['numbers'];  
                }
                $new_check_val[$rs['order_number'].'_'.$rs['sku']."_".$rs['specifications']]=$rs;
            }
            
            //删除异常的数据
            $wraning_data=$this->fun->getdatabasesdetail("db_factory_check_warning"," AND check_id=".$check_data_id);
            $wraning_datas=json_decode($wraning_data['warning_data'],true);
            $wraning_datas=$wraning_datas==null?array():$wraning_datas;
            foreach($wraning_datas as $i=>$rs){
                $new_wraning_val[$rs['order_number'].'_'.$rs['sku']."_".$rs['specifications']]=$rs;
            }
            
            unset($new_wraning_val[$key]); //删除核对正常的错误提醒消息
            $upinfo=$new_check_val[$key];
            $new_check_val[$key]['goods_num']=$upinfo['numbers'];
            unset($new_check_val[$key]['checkstatus']);unset($new_check_val[$key]['skuerror']);
            unset($new_check_val[$key]['styleerror']);unset($new_check_val[$key]['numbererror']);
            $total_num=$upinfo['numbers']-$upinfo['goods_num']+$checkinfo['total_num'];
            $total_price=($upinfo['numbers']-$upinfo['goods_num'])*$upinfo['costprice']+$checkinfo['total_price'];
            $new_check_arr=array();
            foreach($new_check_val as $index=>$checkinfo){
                $new_check_arr[]=$checkinfo;
            }
            $check_data_json=json_encode($new_check_arr);
            $changearr=array('check_data_json'=>$check_data_json,'total_num'=>$total_num,'total_price'=>$total_price);
            //dump($new_check_arr);
            //echo 'update---------<br /><br />';
            
            $this->db->update('db_factory_recive_check',
            array('check_data_json'=>$check_data_json,'total_num'=>$total_num,'total_price'=>$total_price)," id=".$check_data_id);
            //echo $this->db->last_query();
            if(count($new_wraning_val)<=0){
                $this->db->delete('db_factory_check_warning'," check_id=".$check_data_id);    
            }else{
                
                $new_check_arr=array();
                foreach($new_wraning_val as $index=>$checkinfo){
                    $new_check_arr[]=$checkinfo;
                }
                $warning_data_json=json_encode($new_check_arr);
                $this->db->update('db_factory_check_warning',array('warning_data'=>$warning_data_json)," check_id=".$check_data_id);  
               // echo $this->db->last_query();  
            }
        }
    }

    
    public function delReciveCheckInfo(){
        $storeneed=$this->input->get("infoid");
        $this->db->delete('db_factory_recive_check', 'id=' .$storeneed);
        $this->db->delete('db_factory_check_warning', 'check_id=' .$storeneed);
        $history_url=$_SERVER['HTTP_REFERER'];
        echo "<script language='javascript'>location.href='".$history_url."';</script>";  
    }
    
    public function sendGoodsCheckSave(){
        //dump($_POST);
        $check_data=array('check_data_json'=>$_POST['check_data_json'],'total_num'=>$_POST['total_num'],'total_price'=>$_POST['total_price'],
        'factory_num'=>$_POST['factory_num'],'factory_price'=>$_POST['factory_price'],'factory'=>$_POST['factory'],
        'check_day'=>$_POST['check_day'],'creator'=>$_COOKIE['username'],'createtime'=>date("Y-m-d H:i:s"));
        $this->db->insert('db_factory_recive_check', $check_data);
        $insertid = $this->db->insert_id();
        
        $waring_check_data=array('check_id'=>$insertid,'factory'=>$_POST['factory'],'warning_data'=>$_POST['check_error_data_json'],'createtime'=>date("Y-m-d H:i:s"),
            'recive_date'=>$_POST['check_day']);
        $this->db->insert("db_factory_check_warning",$waring_check_data);
        
        echo "<strong><br />对帐数据存储成功，您可以到收件对帐列表查看结果</strong><br />
            <a href='/factory/ajaxbutton?op=goodsReceiptList'>前往查看交运对帐记录</a>";
    }
    
    public function sendGoodsCheckDetail(){
        $search_data=$this->input->get();
        $check_info=$this->fun->getdatabasesdetail("db_factory_recive_check"," and id=".$search_data['id']);
        //echo $this->db->last_query();
        //dump($check_info);
        $check_info_list=json_decode($check_info['check_data_json'],true);
        
        $tpl_data=array('list'=>$check_info_list,'info'=>$check_info);
        $this->tpl->assign($tpl_data);
        $this->tpl->assign("total", count($check_info_list));
        
        $this->tpl->display("factory/sendGoodsCheckDetail.tpl");
    }
}
